0

Sorting

the below code gives the sorted output for the given input of numbers (for ex: input 1 3 2 4 5 output 1 2 3 4 5 and also​ input must contain number of elements). my question is about the expression a[i-1] in the for loop of the below code. i.e when i =1, a[i-1] must be incorrect expression and error should be shown which is not happening in this case (if you refer the code, i have used 1 based indexing​ for input and a[0] mustn't contain anything).. https://code.sololearn.com/cQWil5kL58mc/?ref=app

6th Apr 2018, 5:50 AM
Ravindra Desai
Ravindra Desai - avatar
7 Respostas
+ 1
thanks Gordie ,you were right, the element that was in a[0] was -1!! and i experimented with positive numbers..
6th Apr 2018, 8:12 AM
Ravindra Desai
Ravindra Desai - avatar
+ 1
i say a program sort an array if every array i give it will sort, not only 1 or 2 or any chosen array, so your code is not a true array sorting code you did not used a[0], so if you enter negative values, may you have a value printed that you not entered and if you enter n as 10, a[10] is an invalid memory
6th Apr 2018, 8:14 AM
đŸ‡źđŸ‡· M N
0
your code has some mistakes: 1. arrays in c++ start at index 0 not 1 2. for sorting an array with algorithms like bubble sort, you need two nested for not only 1, search for bubble sort and try to do it ask if you have any other questions
6th Apr 2018, 6:35 AM
đŸ‡źđŸ‡· M N
0
yes i am aware that the index starts with 0...i am writing a code not of any specific kind of sorting like bubble sort, quick sort, insertion sort or of some other kind..here my question is it must give an error but,its not doing so..why?
6th Apr 2018, 6:53 AM
Ravindra Desai
Ravindra Desai - avatar
0
in cpp array bounds never check with compiler or at runtime, so it's programmers responsibilities to correctly code. however if you have any mistakes in arrays bounds or some where else, the result of running your programm will not be as what you expect. for example the code you write will not sort an array, but no errors occures
6th Apr 2018, 6:59 AM
đŸ‡źđŸ‡· M N
0
but it is sorting the array..yes if you give the input for ex: 5 elements 5 4 3 2 1 or 5 1 3 4 2 , it won't exactly sort as 1 2 3 4 5.... because there is only 1 loop..but if u give 1 3 2 5 4 or 2 1 4 3 5, here according to the code, a[0] doesn't contain anything and hence for a[i-1](when i=1) the entire loop must not produce any result or must produce any garbage value​ for a[0] which in this case it is not..
6th Apr 2018, 7:32 AM
Ravindra Desai
Ravindra Desai - avatar
0
đŸ‡źđŸ‡· M N ,i totally agree with you a program must produce correct output for every given input..but it doesn't mean that every program you create must resemble some or the other program..for ex i was creating this program not of bubble sort or some specific kind.. and​ a program need not be of some specific kind..it should just do what the coder wants to be done..
6th Apr 2018, 8:35 AM
Ravindra Desai
Ravindra Desai - avatar