Ad Code

Using Selection Sort Algorithm example

The following code segment sorts an array of integers using “selection sort” algorithm.
for (i=0; i < N-1; i++) {
min = i;
for (j = i; j < N; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;

We break it into smaller fragments by making smaller functions out of different steps in the algorithm as follows:

int minimum (int a[ ], int from, int to)
{
int min = from;
for (int i = from; i <= to; i++)
if (a[i] < a[min])
min = i;
 return min;
 }
void swap (int &x, int &y)
{
int temp = x;
x = y;
y = temp;
 }

The sort function now becomes simpler as shown below.

for (i=0; i < N-1; i++)
{
min = minimum (a, i, N-1);
swap(a[i], a[min]);
}


Reactions

Post a Comment

0 Comments