I am using Turbo C, and I’ve some query about my code. I’m just perplexed… The program first asks for a list of numbers(you shouldn’t type more than 20). As the user types in the numbers, they are placed in the array list[]. Once the user terminates the list by typing 0*(which is not placed on the list)*, the program then calls the sort() function, which sorts the values in the list. At the last part, which has a comment of /*I AM NOW CONFUSED WITH THIS PART*/, is the part where I need your help… Kindly help me out.

File Edit Run Compile Project Options Debug Break/watch
╒════════════════════════════════════ Edit ════════════════════════════════════╕
│ Line 1 Col 43 Insert Indent Tab Fill Unindent * C:NONAME.C │
│ │
│ #define MAXSIZE 20 /* size of buffter */ │
│ void sort(int[], int); /* prototype */ |
│ |
│ main() |
│ { |
│ static int list[MAXSIZE]; /* buffer for numbers */ |
│ int size = 0; /* size 0 before input */ |
│ int dex; /* index of array */ |
│ do /* get list of numbers */ |
│ { |
│ printf("Type number: "); |
│ scanf("%d", &list[size]); |
│ } |
│ while(list[size++] != 0); /* exit loop on 0 */ |
│ |
│ sort(list,--size); /* sort nubmers */ |
│ for(dex=0; dex<size; dex++) /* print sorted list */ |
│ printf("%d\n", list[dex]); |
│ |
│ getche(); |
│ } |
│ |
│ void sort(int list[], int size) |
│ { |
│ int out, in, temp; /* I AM NOW CONFUSED */ |
│ |
│ for(out=0; out<size-1; out++) /* IN THIS PART! */ |
│ for(in=out; in<size; in++) |
│ if(list[out] > list[in]) |
│ { |
│ temp=list[in]; |
| list[in]=list[out]; |
│ list[out]=temp; |
│ } |
│ } |
│ |
│ |
├─────────────────────────────────── Watch ────────────────────────────────────┤
│ │
└──────────────────────────────────────────────────────────────────────────────┘
F1-Help F5-Zoom F6-Switch F7-Trace F8-Step F9-Make F10-Menu NUM
It’s just code that is meant to sort the array elements but it’s never going to work in its current form since:
will overwrite
list[out]withlist[in]without ever preserving the original contents oflist[out].The best way to swap two variables is with something like:
And, please, for the love of whatever deity you believe in, don’t do this 🙂
So, if your question is how to sort the data, then the following pseudo-code should help. I’d provide C code but, on the off chance that this is homework, you should do some of the work yourself a.
This is a bubble sort variation which exits as soon as the list is sorted (well, after one pass with no swaps). Some naive variants will simply keep going for roughly
n2times regardless.a If you’d like to indicate in a comment that it’s not homework, I’d be happy to provide the C code. Just be aware (if you’re planning to lie to me) that your educators will almost certainly be able to see that code and you will probably fail in that case (or be expelled for blatant plagiarism).
And, since you’ve stated it’s not homework, here’s a complete C program illustrating it:
Running this with:
gives you the output: