Solution Review 2: Sort an Array
This lesson will give a detailed solution review of the problem in the previous lesson.
We'll cover the following...
Solution: Sort
Press + to interact
#include<iostream>using namespace std;//Recursive function to sort the arrayvoid SortArray(int arr[], int startIndex, int size){// find the minimum element in the unsorted subarray[i..n-1]// and swap it with arr[startIndex]int min = startIndex;for (int j = startIndex + 1; j < size; j++){// if arr[j] element is less, then it is the new minimumif (arr[j] < arr[min])min = j; // update index of min element}//swap values at two indices in the arrayint Swap= arr[startIndex];arr[startIndex]= arr[min];arr[min]= Swap;// base caseif (startIndex + 1 < size) { //if one element is left to be sortedSortArray(arr, startIndex + 1, size); // recursive case}}void printSortArray(int *numbers, int size){SortArray(numbers, 0, size);//call the recursive functionfor (int i=0;i<size;i++)//print elements of the arraycout << numbers[i] << ' ';}//Driver functionint main(){int array[] = {3, 2, 9, 1, 8};// define an arrayint size=5;//define the size of arraycout<<"Sorted Array:\n";printSortArray(array, size);//call the print functionreturn 0;}
Understanding the Code
A recursive code can be ...
Access this course and 1400+ top-rated courses and projects.