-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort.cpp
95 lines (77 loc) · 1.93 KB
/
sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Menu driven program for Bubble Sort, Selection Sort, Insertion Sort.
#include <iostream>
using namespace std;
int main()
{
char ch;
int a[20];
int i, j, k, n;
int temp;
cout << "\n\t\t\tEnter the number of elements in array\n\t\t\t";
cin >> n;
cout << "\n\t\t\tEnter the elements of array\n\t\t\t";
for( i = 0; i < n; i++ ){ cout << "\n\t\t\t"; cin >> a[i]; }
cout << "\n\t\t\tPress a for Bubble sort\n\t\t\t";
cout << "\n\t\t\tPress b for Selection sort\n\t\t\t";
cout << "\n\t\t\tPress c for Insertion sort\n\t\t\t";
cout << "\n\t\t\tEnter your choice\n\t\t\t";
cin >> ch;
if(ch == 'a' || ch == 'A') // Bubble Sorting
{
for( i =0; i < n; i++)
for( j = 0; j < n-1; j++)
if( a[j] > a[j+1] )
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
cout << "\n\t\tSorted array list in ascending order via Bubble Sort\n\n\t\t";
for( i = 0; i < n; i++ )
cout << a[i] << " ";
cout << " \n\n ";
}
else if(ch == 'b' || ch == 'B') // Selection Sort
{
int big;
int index;
for( i = n-1; i > 0; i-- )
{
big = a[0];
index = 0;
for( j = 0; j <= i; j++ )
if( a[j] > big )
{
big = a[j];
index = j;
}
a[index] = a[i];
a[i] = big;
}
cout << "\n\t\t\tArray after Selection Sort\n\t\t\t";
for( i = 0; i < n; i++ )
cout << a[i] << " ";
cout << "\n\n";
}
else if(ch == 'c' || ch == 'C') // Insertion Sort
{
int key;
for( j = 1; j < n; j++ )
{
key = a[j];
i = j-1;
while( i >= 0 && a[i] > key )
{
a[i+1] = a[i];
i = i-1;
}
a[i+1] = key;
}
cout << "\n\t\t\tArray after Insertion Sort\n\t\t\t";
for( i = 0; i < n; i++)
cout << a[i] << " ";
cout << "\n\n";
}
else
cout << "\n\t\t\tWrong Choice\n\n";
}