Professional Documents
Culture Documents
Lecture 14
Sorting
Compiled by
G. N. Pachshenko
Definition:
A sorting algorithm is an algorithm that puts
elements of a list in a certain order.
Unsorted array:
Sorted array:
It is often necessary to arrange the elements in
an array in numerical order
• Simple sorts
– Insertion sort
– Selection sort
• Efficient sorts
– Merge sort
– Heapsort
– Quicksort
• Bubble sort and variants
– Bubble sort
– Shell sort (Shell is a surname)
– Comb sort
• Distribution sort
– Counting sort
– Bucket sort
– Radix sort
Bubble Sort
In the bubble sort, as elements are sorted they
gradually "bubble" (or rise) to their proper
location in the array, like bubbles rising in a glass
of soda. The bubble sort repeatedly
compares adjacent elements of an array.
The first and second elements are compared and
swapped if out of order.
Then the second and third elements are compared
and swapped if out of order.
int main()
{
int num[5];
int i, j, flag = 1; // set flag to 1 to start first pass
int temp; // holding variable
return 0;
} // to demonstrate it
Exchange Sort
The exchange sort is similar to the bubble sort,
in that it compares elements of the array and
swaps those that are not in their proper
positions.
The difference between these two sorts is the
manner in which they compare the elements.
int main()
{
int num[5];
int i, j, flag = 1;
int temp, first;
int n = 5;
return 0;
}
For array of 5 elements:
i=4 j=1
i=4 j=2
i=4 j=3
i=4 j=4
i=3 j=1
i=3 j=2
i=3 j=3
i=2 j=1
i=2 j=2
i=1 j=1
insertion sort
The insertion sort works in a slightly different
way. It always maintains a sorted sublist in the
lower positions of the list. Each new item is then
“inserted” back into the previous sublist such
that the sorted sublist is one item larger.
for(j = 1; j < n; j++) // Start with 1 (not 0)
{
key = num[j];
for(i = j - 1; (i >= 0) && (num[i] < key); i--)
// Smaller values move up
{
num[i+1] = num[i];
}
num[i+1] = key;
//Put key into its proper location
}