Implement the Selection Sort algorithm by taking single character input(10 lette
ID: 3859101 • Letter: I
Question
Implement the Selection Sort algorithm by taking single character input(10 letters) from the user. Perform the bubble sort on 10 integers input by the user in a descending order(bigger to smaller). Write a method that accepts an integer array as a parameter and sorts it using the insertion sort algorithm. Write a method that accepts an integer and an array of integers, and returns true if the integer is contained in the array. You may assume that the array is sorted, and your method should use a binary search. You can use recursive or iterative approach to solve the problem.Explanation / Answer
C++ code attched with all four methods:
#include <iostream>
using namespace std;
void print_charArray(char arr[], int len){
for(int i=0;i<len;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
void print_numArray(int arr[], int len){
for(int i=0;i<len;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
void selection_sort(char arr[],int len){
char min;
int minindex;
for(int i=0;i<len;i++){
min = arr[i];
minindex = i;
for(int j=i;j<len;j++){
if(arr[j]<min){
min = arr[j];
minindex = j;
}
}
arr[minindex] = arr[i];
arr[i] = min;
}
}
void bubble_sort(int arr[],int len){
int temp;
for(int i=0;i<len;i++){
for(int j=0;j<len-i-1;j++){
if(arr[j]<arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void insertion_sort(int arr[],int len){
int j, cur;
for(int i=1;i<len;i++){
j=i-1;
cur = arr[i];
while(j>=0 && cur<arr[j]){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = cur;
}
}
bool binary_search(int arr[],int len, int num){
int mid;
int start = 0;
int end = len;
while(start<end){
mid = (start+end)/2;
if(arr[mid]==num){
return true;
}
else if(arr[mid]<num){
start=mid+1;
}
else{
end=mid;
}
}
return false;
}
int main() {
char c;
char charArr[10];
cout<<"Q1. Selection Sort"<<endl;
cout<<"Enter 10 letters:"<<endl;
for(int i=0;i<10;i++){
cin>>c;
charArr[i] = c;
}
selection_sort(charArr,10);
print_charArray(charArr,10);
cout<<endl;
int num;
int numArr[10];
cout<<"Q2. Bubble Sort"<<endl;
cout<<"Enter 10 Integers:"<<endl;
for(int i=0;i<10;i++){
cin>>num;
numArr[i] = num;
}
bubble_sort(numArr,10);
print_numArray(numArr,10);
cout<<endl;
int numArr2[10];
cout<<"Q3. Insertion Sort"<<endl;
cout<<"Enter 10 Integers:"<<endl;
for(int i=0;i<10;i++){
cin>>num;
numArr2[i] = num;
}
insertion_sort(numArr2,10);
print_numArray(numArr2,10);
cout<<endl;
cout<<"Q4. Binary Search"<<endl;
cout<<"Enter number to be searched:"<<endl;
cin>>num;
cout<<binary_search(numArr2,10,num)<<endl;
return 0;
}