- A fundamental task of computer science
- given an array , put the array in order
sort(a);
a=0,2,3,6,9
Sorting Strategies
- Bubble Sort
- take the unsorted array and start at the top
- traverse the list until you find an element out of order
- using pairwise exchanges move the out of order element toward the top of the list until it is in order
- continue until the end of the list
- once an out of order element is found we float it to the correct position
- 39026
- 30926
- 03926
- 03296
- 02396
- 02369
- nobody uses bubblesort for anything serious
- better methods:
- mergesort
- quicksort
- if the list is of size > 1 then
- divide the list into two sublists
- sort each sublist
- join the two sublists
- else
- do nothing
- these are recursive sorting algorithms
- all the actio nhappens in the splitting and joining
//sorts the subvector of 'a' from beginning to end inclusive
{
if (end - begin > 0)
{
int S = split(a,beginning,end)
sort(a,begin,S);
sort(a,S+1,end;
join(a,begin,S,end)
}
- MergeSort
- split is simple
- join is complicated
- QuickSort
- split is complicated
- join is simple
MergeSort
- Split
- splits the list down the middle
- returns (begin + end )/ 2
- Join
- two sorted Lists
- merge them in order
Example
038249
038 249
0<2
2<3
3<4
4<8
8<9
023489
42091
420:91
- 42:0
- 4:2
- 4 //done
- 2 //done
- join(2,4)
- 24
- join(24,0)
- 024
- 9:1
- 9 //done
- 1 //done
- join(9,1)
- 19
- join(024,91)
- 01249
No comments:
Post a Comment