Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program to implement Selection Sort Algorithm. Test your code with b

ID: 3749063 • Letter: W

Question

Write a C++ program to implement Selection Sort Algorithm.

Test your code with both integer and character data. Your main program will be similar to the lab you have done last week (using Insertion Sort). You need to write the Selection Sort function, which might involve a Swap function and finding index for minimum data. Check your class notes for the algorithm.

The Swap function

void Swap(Data A[], int I, int J)

{

Data temp;

  temp = A[I];

  A[I] = A[J];

A[J] = temp;

}

The function for finding the index for the minimum data:

int Min(Data A[], int I, int N)

{

  int min = I;

  int j = I+1;

  while(j <= N)

{

if (A[j] < A[min]) min = j;

j++;

}

  return min;

}

Explanation / Answer

#include<iostream>

using namespace std;

void Swap(int A[],int l,int j)

{

int temp;

temp=A[l];

A[l]=A[j];

A[j]=temp;

}

int Min(int A[],int l,int N)

{

int min=l;

int j=l+1;

while(j<=N)

{

if(A[j]<A[min])

{

min=j;

j++;

}

return min;

}

}

void selectionSort(int A[],int N,int k)

{

int i,j;

for (i = 0; i < N-1; i++)

{

// Find the minimum element in unsorted array

k = i;

for (j = i+1; j < N; j++)

if (A[j] < A[k])

k = j;

// Swap the found minimum element with the first element

Swap(A,k, i);

}

}

void printArray(int A[], int size)

{

int i;

for (i=0; i < size; i++)

{

cout<< A[i];

  

}

}

int main()

{

int N, i;

cout<<" Enter the number of data element to be sorted: ";

cin>>N;

int A[N];

for(i = 0; i < N; i++)

{

cout<<"Enter element "<<i+1<<": ";

cin>>A[i];

}

int l,k;

l=A[0];

k=Min(A,l,N);

selectionSort(A, N,k);

cout<<" SORTED ARRAY ";

printArray(A, N);

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote