Sorting | Sololearn: Learn to code for FREE!

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

cpp

4/6/2018 5:50:25 AM

Ravindra Desai

8 Answers

New Answer

+1

thanks Gordie ,you were right, the element that was in a[0] was -1!! and i experimented with positive numbers..

+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

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

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?

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

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..

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..