The exchange sort starts with the first element in an array and then compares it
ID: 650075 • Letter: T
Question
The exchange sort starts with the first element in an array and then compares it with each
item in the array in order. If the elements are out of order, they are swapped. Once every
element is checked, the sort moves to the second element and compares it with all
elements except for the first. This continues until the array is sorted.
Create Program: C++
Create a 10 integer array and fill it with random integers between
1and 100. Then using the exchange sort, sort it so that the lowest values are first in the
array and larger numbers are last. Here is an example of a run
array before sorting: 83 90 46 93 5 22 30 2 70 6
array after sorting: 2 5 6 22 30 46 70 83 90 93
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main() {
int n[10],i,j,temp;
printf("Ten random numbers in [1,100] ");
for (i = 0; i < 10; i++) {
n[i] = rand() % 100 + 1;//set rand() function with precision 100+1 to get the random values below 100
}
for(i=0;i<10;i++){
printf("%d ",n[i]);
}
for(i=0;i<10;i++){ //sort the values
for(j=i+1;j<10;j++){
if(n[i]>n[j]){ //check the array with its first number
temp=n[i]; //swap if first value is greater than other values in array
n[i]=n[j];
n[j]=temp;
}
}
}
printf(" "); //print new line
for(i=0;i<10;i++){
printf("%d ",n[i]); //print sorted array
}
return 0;
}
Expected Output :
Ten random numbers in [1,100]
42 68 35 1 70 25 79 59 63 65
1 25 35 42 59 63 65 68 70 79
--------------------------------
Process exited with return value 0
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.