#include <stdio.h>
void swap(int *number1, int *number2)
{
int temp;
temp = *number1;
*number1 = *number2;
*number2 = temp;
}
void selectionSort(int array[], int outer_counter, int inner_counter, int len)
{
int i, j, min;
outer_counter = 0;
inner_counter = 0;
for(i = 0; i < len; i++)
{
outer_counter++;
min = 1;
for(j = i+1; j < len; j++)
{
inner_counter++;
if(array[j] < array[min])
min = j;
}
swap(&array[i], &array[min]);
}
printf("For the outer loop we need: %d steps.\n", outer_counter);
printf("For the inner loop we need: %d steps.\n", inner_counter);
}
void bubbleSort(int array[], int outer_counter, int inner_counter, int len)
{
int i, j;
outer_counter = 0;
inner_counter = 0;
for(i = len - 1; i >= 0; i--)
{
outer_counter++;
for(j = 1; j <= i; j++)
{
inner_counter++;
if(array[j-1] > array[j])
swap(&array[j-1], &array[j]);
}
}
printf("For the outer loop we need: %d steps.\n", outer_counter);
printf("For the inner loop we need: %d steps.\n\n", inner_counter);
}
int main()
{
int test1[11] = {45, 18, 0, 500, 486, 212, 318, 1000, 1008, 1, 4};
int test2[9] = {800, 3, 200, 22, 66, 23, 32, 10, 9};
int test3[6] = {33, 334, 3, 3334, 333, 33334};
int outer_counter, inner_counter;
printf("In selection sort for the first array: \n");
selectionSort(test1, outer_counter, inner_counter, 11);
printf("In bubble sort for the the first array: \n");
bubbleSort(test1, outer_counter, inner_counter, 11);
printf("In selection sort for the second array: \n");
selectionSort(test2, outer_counter, inner_counter, 9);
printf("In bubble sort for the second array: \n");
bubbleSort(test2, outer_counter, inner_counter, 9);
printf("In selection sort for the third array: \n");
selectionSort(test3, outer_counter, inner_counter, 6);
printf("Ina bubble sort for the third array: \n");
bubbleSort(test3, outer_counter, inner_counter, 6);
return 0;
}
This post has been edited by erkant: 29 March 2012 - 01:55 PM

New Topic/Question
Reply



MultiQuote




|