Sorting:-
Like Searching, I will cover list sorting very
briskly as I have given it a good coverage in my last section of this
tutorial. But for now we'll see, just a "Timepass" sort. I call
it 'Timepass' because it actually consumes a lot of time in sorting and
takes too many passes. This procedure has been devised by me so I would
not suggest you to strictly follow it. Resembles very much to Bubble sort.
Let's see...
Algorithm:-
Step-1: Find out the smallest element from the LIST
Step-2: Swap it with the FIRST element of the list
Step-3: Now consider the LIST beyond the FIRST element of the current list
Step-4: Repeat from step-1 to 4 for N times provided you have N elements
in the LIST
Let us see its C
implementation:-
int list[N], least, index,
pass, temp_index;
...
...
...
/*step-4: Repeat from step -1 to 4 for
N times i.e N passes*/
for(pass=0;pass<=N-1;pass++)
{
/*step-1:find the smallest from the LIST*/
least=list[pass];
for(index=pass+1;index<=N-1;index++)
if(least>list[index])
{
least=list[index];
temp_index=index;
}
/*step-2: swap the least with the FIRST element of the
list*/
temp=list[pass]; /*the first element*/
list[pass]=least;
list[temp_index]=temp;
/*Now
consider the LIST beyond the FIRST element of the current list which
is been done by incrementing the value of PASS */
}
for(index=0;index<=5;index++)printf("\n%d", list[index]); /*print
the sorted list out*/
..
..
..
Note:- Given
above is just a portion of code and you can use it in your program. You
can request for the complete program through e-mail.
Related Operations:
Addition
and Deletion of elements
Traversing of list
Searching for a particular Key
Sorting of list in ascending and descending order |