Professional Documents
Culture Documents
Haider Ali
http://faculty.ksu.edu.sa/haiderali
April 2009
Bubble Sort
• Divide list into sorted and unsorted sublists
• Smallest element in the unsorted sublist is
“bubbled” up into the sorted sublist
• Repeat until done:
– Compare adjacent pairs of records/nodes
– If the pair of nodes are out of order, exchange them,
and continue with the next pair of records/nodes
– If the pair is in order, ignore them and continue with
the next pair of nodes
Selection Sort
• Divide the list into two sublists: sorted and
unsorted, with the sorted sublist preceding
the unsorted sublist
• In each pass,
– Find the smallest item in the unsorted sublist
– Exchange the selected item with the first item
in the sorted sublist
Insertion Sorts
• Commonly used by card players: As each
card is picked up, it is placed into the
proper sequence in their hand
• Divide the list into a sorted sublist and an
unsorted sublist
• In each pass, one or more pieces of data
are removed from the unsorted sublist and
inserted into their correct position in a
sorted sublist
8
Merge-Sort
Merge-sort(S, n)
• Divide S into two sequences S1 and S2
• Recursively sort S1 and S2
• Merge S1 and S2 into a unique sorted
sequence
10
11
Merge - Algorithm
Void merge(a[], left, mid, right)
{
for (i = mid+1; i > left; i--)
b[i-1] = a[i-1];
for (j = mid; j < right; j++)
b[right+mid-j] = a[j+1];
12
14
15
Partition - Algorithm
int partition(a, left, right)
{
p = a[left]
L = left + 1,
R = right;
while (L < R)
{
while (L < right && a[L] < p)
L++;
while (R > left && a[R] >= p)
R--;
if (L<R)
swap(a[R],a[P])
}
a[left] = a[R];
a[R] = p;
}
16
while(l<=r)
{
while(L<right && a[L]<p) L++;
while (R>left && a[R]>=p) R--;
if(L<R)
swap(a[L],a[R]);
};
a[left]=a[R];
a[R]=p;
return R;
};
17
i=partition(a,left,right);