Tuesday, June 27, 2006

Bubble Sort/Insertion Sort

Methods of Sorting
1. Bubble Sort
Compare the adjacent elements and set the higher index element to the highest among the two. a[i+1] = max(a[i],a[i+1]). So each pass you are actually putting the highest element at the end of the array.
Sample Code:

for (int i = 0; i < data.Length; i++)
for (int j = 0; j < data.Length - 1; j++)
if (data[j] > data[j + 1])
{
tmp = data[j];
data[j] = data[j + 1];
data[j + 1] = tmp;
}


2. Insertion Sort
In Insertion Sort we try to insert one element by element into the already sorted array. So every time we insert a new element we actually shift the whole array.

for (int i = 0; i <= data.Length; i++) {
int j = i;
while (j > 0 && data[i] < data[j - 1])
j--;
int tmp = data[i];
for (int k = i; k > j; k--)
data[k] = data[k - 1];
data[j] = tmp;
}

About Sorting:
http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=sorting

No comments: