-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsortingAlgorithm.cpp
126 lines (103 loc) · 2.73 KB
/
sortingAlgorithm.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
126
// Buat kode program untuk mengimplementasikan algoritma Sorting: Bubble Sort, Selection Sort, Merge Sort dan Quick Sort. Lalu lengkapi data pada tabel berikut.
#include <iostream>
using namespace std;
//Function Declaration
void BubbleSort(int *arr, int size);
void SelectionSort(int *arr, int size);
void MergeSort(int *arr, int left, int right);
void Merge(int *arr, int aLeft, int aRight, int bLeft, int bRight);
void QuickSort(int *arr, int left, int right);
//Bubble Sort
void BubbleSort(int *arr, int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
}
}
}
}
//Selection Sort
void SelectionSort(int *arr, int size) {
for (int i = 0; i < size; ++i) {
int minIndex = i;
for (int j = i+1; j < size; ++j) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}
//Merge Sort
void MergeSort(int *arr, int left, int right) {
if (left == right) return;
int mid = (left + right) / 2;
MergeSort(arr, left, mid);
MergeSort(arr, mid+1, right);
Merge(arr, left, mid, mid+1, right);
}
void Merge(int *arr, int aLeft, int aRight, int bLeft, int bRight) {
int size = bRight - aLeft + 1;
int tmp [size];
int tIndex = 0;
int aIndex = aLeft;
int bIndex = bLeft;
while (aIndex <= aRight && bIndex <= bRight) {
if (arr[aIndex] <= arr[bIndex]) {
tmp[tIndex] = arr[aIndex];
++aIndex;
}
else {
tmp[tIndex] = arr[bIndex];
++bIndex;
}
++tIndex;
}
while (aIndex <= aRight) {
tmp[tIndex] = arr[aIndex];
++tIndex;
++aIndex;
}
while (bIndex <= bRight) {
tmp[tIndex] = arr[bIndex];
++tIndex;
++bIndex;
}
for (int i = 0; i < size; ++i) {
arr[aLeft+i] = tmp[i];
}
}
//Quick Sort
int partition(int *arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high - 1; 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 pivot = partition(arr, low, high);
QuickSort(arr, low, pivot - 1);
QuickSort(arr, pivot + 1, high);
}
}
int main()
{
int arr[1000000];
for (int i = 0; i < 1000000; i++) {
cout << i << endl;
arr[i] = 10;
}
BubbleSort(arr, 1000000);
for (int i = 0; i < 1000000; i++) {
cout << arr[i] << " ";
}
cout << endl;
}