Thursday, April 23, 2009

5 - Sorting Algorithm : Shell Sort

Another sorting algorithm is Shell Sort. It is based on insertion sort. This sorting method performs multiple passes through the array. Every time it passes the array it performs insertion sort. It divide the arry into several sets. A set grows every time the algorithm works on the array. Of course we need to understand that each members' location is not adjacent to each other (NOT CONTIGOUS). I will present two Shell sort alogoritms : one is for ascending sort and the other is for descending sort :

The first one is ascending sort :
#include "iostream"
using namespace std;

int main(void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;
int increment;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

increment = 3;
while (increment > 0)
{
for (i=0; i < 8; i++)
{
j = i;
temp = data[i];
while ((j >= increment) && (data[j-increment] > temp))
{
data[j] = data[j - increment];
j = j - increment;
}
data[j] = temp;
}
if (increment/2 != 0)
increment = increment/2;
else if (increment == 1)
increment = 0;
else
increment = 1;
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

return 0;
}

And here is for descending sort :
#include "iostream"
using namespace std;

int main(void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;
int increment;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

increment = 3;
while (increment > 0)
{
for (i=0; i < 8; i++)
{
j = i;
temp = data[i];
while ((j >= increment) && (data[j-increment] < temp))
{
data[j] = data[j - increment];
j = j - increment;
}
data[j] = temp;
}
if (increment/2 != 0)
increment = increment/2;
else if (increment == 1)
increment = 0;
else
increment = 1;
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

return 0;
}