-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorting.cpp
125 lines (104 loc) · 2.44 KB
/
Sorting.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
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
#include <bits/stdc++.h>
using namespace std;
#define lint long long int
void selectionSort(int arr[],int n){
for(int i=0;i<n-1;i++){
int min_i=i;
for(int j=i+1;j<n;j++){
if(arr[min_i]>arr[j]){
min_i=j;
}
}
swap(arr[min_i],arr[i]);
}
}
void bubbleSort(int arr[],int n){
for(int i=0;i<n-1;i++){
bool isSorted=true;
for(int j=0;j<n-i-1;j++){
if(arr[j]>arr[j+1]){
swap(arr[j],arr[j+1]);
isSorted=false;
}
}
if(isSorted)
break;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void insertionSort(int arr[],int n){
for(int i=1;i<n;i++){
int toSwap=arr[i];
int j=i-1;
while(arr[j]>toSwap && j>=0){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=toSwap;
}
}
void merge(int arr[], int l, int m, int r){
vector<int> temp;
int first=l;
int second=m+1;
while(first<=m && second<=r){
if(arr[first]<=arr[second]){
temp.push_back(arr[first]);
first++;
}
else{
temp.push_back(arr[second]);
second++;
}
}
while(first<=m){
temp.push_back(arr[first]);
first++;
}
while(second<=r){
temp.push_back(arr[second]);
second++;
}
for(int i=l;i<=r;i++){
arr[i]=temp[i-l];
}
}
void mergeSort(int arr[], int l, int r){
if(l>=r) return;
int mid=l+(r-l)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,mid,r);
}
void quickSort(int arr[], int low, int high) {
if (low >= high) return;
int i = low;
int j = high;
int pivot = arr[low];
while (i <= j) {
while (i <= j && arr[i] <= pivot) {
i++;
}
while (i <= j && arr[j] > pivot) {
j--;
}
if (i < j) {
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[low], arr[j]);
quickSort(arr, low, j - 1);
quickSort(arr, j + 1, high);
}
int main() {
int arr[]={3,4,2,1,187,-1,1};
quickSort(arr,0,7);
for(auto a:arr){
cout<<a<<" ";
}
}