I have the solution to the problem I did... The part I\'m having a problem with
ID: 3566804 • Letter: I
Question
I have the solution to the problem I did... The part I'm having a problem with is:
A written description that describes to me HOW the sorts are working. I want you to put it into written words - you can reference the results in your program. Your description should be at least 8 sentences long. ("On the first pass through, the following numbers were swapped because.....") If you have completed this exercise, you should be able to give me a mini-lecture on how it worked.
The solution is:
#include <iostream>
using namespace std;
void bubble_sort(int array[]) {
int n=8;
for (int c = 0 ; c < ( n - 1 ); c++)
{
for (int d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
int swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
for(int i=0;i<8;i++)
cout<<array[i]<<" ";
cout<<endl;
}
}
void selection_sort(int num[])
{
int numel = 8;
int j, min, minidx, grade;
for(int i=0;i<numel-1;i++)
{
min = num[i]; // assume minimum is the first array element
minidx = i; // index of minimum element
for(j = i + 1; j < numel; j++)
{
if (num[j] < min) // if we
Explanation / Answer
Bubble sort:
In main part of the bubble sort function we have a nested 'for' loop i.e, a 'for' loop inside a 'for' loop.
For ith iteration of the outer 'for' loop we are calculating the ith smallest number in the array and storing it in the array using the inner for loop.
In the inner for loop we are comparing the jth element of the array with the ith element and we are swapping it if the ith element is larger than jth element so that ith element of the array becomes the ith smallest element of the array after the completition of the ith iteration of the outer loop. So, after n iterations of the outer loop the array gets sorted.
Ex:
Input: 5 4 3 2 1
THis is how array gets changed for every iteration.
1 5 4 3 2
1 2 5 4 3
1 2 3 5 4
1 2 3 4 5
----------------------------------------------------------
Selection sort:
Selection sort also works in the same way as the bubble sort but in selection sort we reduce the no. of swapping operations.
Instead of swapping every time like in bubble sort, the inner 'for' loop is keeping track of the ith least element value and its position and after the completion of inner loop we are swapping the ith element with the ith least element if the ith element is not the ith least element.
Ex:
Input: 5 4 3 2 1
THis is how array gets changed for every iteration.
1 4 3 2 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5