Write a C program that implement a function that does a selection sort of an arr
ID: 3629113 • Letter: W
Question
Write a C program that implement a function that does a selection sort of an array of integers using this skeleton code (***Just Fill in the "<your code here>")
The function should sort the array x using the selection sort algorithm.
void sort(int x[], int size);
int a[] = {1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8};
void main(void)
{
sort(a, 16);
for(;;) {} /* wait forever */
}
void sort(int x[], int size)
{
int iUnsorted; // index of the first number in the unsorted array
// increment by 1 after each pass through inner loop
int iMin; // index of the most negative so far on this pass
int iNext; // index of the next number to compare to x[iMin]
int temp; // used for swapping array numbers
for (iUnsorted=0; iUnsorted < size-1; iUnsorted++)
{
iMin = iUnsorted;
for (iNext=iUnsorted+1; iNext < size; iNext++)
{
<your code here>
}
<your code here>
}
}
Explanation / Answer
// code shown in red color...
void sort(int x[], int size);
int a[] = {1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8};
void main(void)
{
sort(a, 16);
for(;;) {} /* wait forever */
}
void sort(int x[], int size)
{
int iUnsorted; // index of the first number in the unsorted array
// increment by 1 after each pass through inner loop
int iMin; // index of the most negative so far on this pass
int iNext; // index of the next number to compare to x[iMin]
int temp; // used for swapping array numbers
for (iUnsorted=0; iUnsorted < size-1; iUnsorted++)
{
iMin = iUnsorted;
for (iNext=iUnsorted+1; iNext < size; iNext++)
{
if (x[iNext] < x[iMin])
iMin = iNext;
}
temp = x[iUnsorted];
x[iUnsorted] = x[iMin];
x[iMin] = temp;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.