1. The purpose of a sorting algorithm is to order/categorize set of items within a series of items.
I. Write a program/method to find a minimum number in an integer numbers array.
II. Write a program/method to swap two numbers in the above array when the indices are given.
III. Now combine the above two methods and implement selection sort algorithm. You must call the above two methods in your sorting program.
IV. Write a program/method to generate an array of random numbers.
V. Now test your selection sort algorithm with a random number array.
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
int findMinimumNumber(int items[], int size);
void selectionSort(int items[],int size);
int main()
{
int items[10], size=10,i;
time_t t;
srand((unsigned) time(&t));
//test your selection sort algorithm with a random number array.
printf("Random numbers from 0 to 49:\n");
for( i = 0 ; i < size ; i++ ) {
items[i]=rand() % 50;
printf("%d ",items[i]);
}
printf("\n\nRandom numbers from 0 to 49 after sorting:\n");
selectionSort(items,size);
for( i = 0 ; i < size ; i++ ) {
printf("%d ",items[i]);
}
getchar();
return 0;
}
//Write a program/method to find a minimum number in an integer numbers array.
int findMinimumNumber(int items[], int size){
int max = 0, j;
for (j = 1; j <= size; j++)
{
if (items[j] > items[max])
{
max = j;
}
}
return max;
}
//Write a program/method to swap two numbers in the above array when the indices are given.
void swapTwoNumbers(int& number1,int& number2)
{
int temp = number1;
number1 = number2;
number2 = temp;
}
// Now combine the above two methods and implement selection sort algorithm.
//call the above two methods in your sorting program.
void selectionSort(int items[], int size)
{
int temp, minIndex, j;
for (j = size - 1; j >= 1; j--)
{
minIndex = findMinimumNumber(items, j);
swapTwoNumbers(items[minIndex],items[j]);
}
}
Comments
Leave a comment