-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMenu_of_Sorting.cpp
More file actions
151 lines (124 loc) · 2.77 KB
/
Copy pathMenu_of_Sorting.cpp
File metadata and controls
151 lines (124 loc) · 2.77 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <iostream>
using namespace std;
void displayArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
}
void selectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}
void insertionSort(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++)
{
if (arr[j] < pivot)
{
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
int main()
{
int n;
cout << "Enter the size of array: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int choice;
cout << "\nOriginal Array: ";
displayArray(arr, n);
cout << "\n===== SORTING MENU =====" << endl;
cout << "1. Bubble Sort" << endl;
cout << "2. Selection Sort" << endl;
cout << "3. Insertion Sort" << endl;
cout << "4. Quick Sort" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
bubbleSort(arr, n);
cout << "\nArray after Bubble Sort: ";
displayArray(arr, n);
break;
case 2:
selectionSort(arr, n);
cout << "\nArray after Selection Sort: ";
displayArray(arr, n);
break;
case 3:
insertionSort(arr, n);
cout << "\nArray after Insertion Sort: ";
displayArray(arr, n);
break;
case 4:
quickSort(arr, 0, n - 1);
cout << "\nArray after Quick Sort: ";
displayArray(arr, n);
break;
default:
cout << "\nInvalid choice!" << endl;
}
return 0;
}