Uploaded by Philosophical Pineapple

Tutorial 5 Sorting Algorithms Answered

advertisement
SOF105 Data Structures
Tutorial (Sorting)
Question 1:
Write a function to sort an array in both ascending and descending order using
1. Selection sort algorithm.
2. Insertion sort algorithm.
3. Bubble sort algorithm.
a)
b)
c)
d)
The user should decide which algorithm to choose (1,2 or 3) and
The user should specify the order (ascending or descending).
The output should display step by step the changes in each pass.
Can you further improve the complexity of any of the above algorithms?
#include <iostream>
#include <array>
#include <vector>
using namespace std;
vector<int> Bubblesort(vector<int> arr, int sizearr){
int first =0;
int second = 1;
int temp;
for(int j =0; j < sizearr-1;j++){
for(int x=0; x < sizearr;x++){
if(arr[x] > arr[x+1]){
temp = arr[x];
arr[x] = arr[x+1];
arr[x+1] = temp;
}
}
}
return arr;
}
vector<int> Insertionsort(vector<int> arr, int sizearr){
int key,j,temp;
for(int x=1;x <= sizearr;x++){
key = arr[x];
j = x-1;
while(j >= 0 && arr[j] > key){
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j+1] = key;
}
Prepared by Saif Kifah
SOF105 Data Structures
return arr;
}
vector<int> Selectionsort(vector<int> arr, int sizearr){
int temp;
for(int x=0;x<=sizearr;x++){
for(int y =x+1; y <= sizearr;y++){
if(arr[x] > arr[y]){
temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
return arr;
}
int main() {
vector <int> arr = {3,7,5,6,2,1,4};
int algo =0;
int order=0;
int sizeofarr;
sizeofarr = sizeof(arr)/sizeof(arr[1]);
cout << "Enter 1 for : Selection sort algorithm " <<endl;
cout << "Enter 2 for : Insertion sort algorithm " <<endl;
cout << "Enter 3 for : Bubble sort algorithm " <<endl;
cout << ":";
cin >> algo;
cout << "Enter 1 for: Ascending order"<<endl;
cout << "Enter 2 for : descending order " <<endl;
cout << ":";
cin >> order;
switch(algo){
case 1:
cout << "You have picked Selection sort algorithm " <<endl;
arr = Selectionsort(arr,sizeofarr);
break;
case 2:
cout << "You have picked Insertion sort algorithm " <<endl;
arr =Insertionsort(arr,sizeofarr);
break;
case 3:
cout << "You have picked Bubble sort algorithm" <<endl;
arr = Bubblesort(arr,sizeofarr);
break;
}
if(order == 1){
Prepared by Saif Kifah
SOF105 Data Structures
cout << "in Ascending order " <<endl;
for(int x= 0; x <= sizeofarr;x++){
cout << arr[x] << ",";
}
}else if(order == 2){
cout << "in Descending order " <<endl;
for(int x= sizeofarr; x >= 0;x--){
cout << arr[x] << ",";
}
}
}
Prepared by Saif Kifah
Download