정렬 C++
2021. 6. 1. 15:45ㆍStudy/CS
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
|
#include <iostream>
using namespace std;
int *arr2;
void swap(int *arr,int a,int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void BubbleSort(int *arr,int len)
{
for(int i = len-1 ; i > 0 ; i--)
{
for(int j = 0 ; j < i ; j++)
{
if(arr[j] > arr[j+1])
{
swap(arr,j,j+1);
}
}
}
}
void SelectionSort(int *arr ,int len)
{
for(int i = 0 ; i < len-1 ; i++)
{
int selection = arr[i];
for(int j = i+1 ; j < len ; j++)
{
if(selection > arr[j])
{
selection = arr[j];
swap(arr, i,j);
}
}
}
}
void InsertionSort(int *arr ,int len)
{
for(int i = 1 ; i < len ; i++)
{
int key = arr[i];
int tmp = i-1;
while((tmp >= 0) && (arr[tmp] > key))
{
arr[tmp+1] = arr[tmp];
tmp--;
}
arr[tmp+1] = key;
}
}
void merge(int *arr ,int len ,int left, int right)
{
int mid = (left+right)/2;
int l = left;
int r = mid+1;
int idx = left;
while(l <= mid && r <= right)
{
if(arr[l] < arr[r])
{
arr2[idx++] = arr[l++];
}
else
{
arr2[idx++] = arr[r++];
}
}
int tmp = l > mid ? r : l;
while(idx <= right)
{
arr2[idx++] = arr[tmp++];
}
for(int i = left ; i <= right ; i++)
{
arr[i] = arr2[i];
//cout << arr[i] << " ";
}
//cout << endl;
}
//divide and conquer
void MergeSort(int *arr ,int len, int left, int right)
{
if(left < right)
{
int mid = (left+right)/2;
MergeSort(arr,len, left, mid);
MergeSort(arr,len, mid+1, right);
merge(arr,len,left,right);
}
}
void QuickSort(int *arr ,int left,int right)
{
if(left >= right) return;
int pivot = left;
int i = pivot + 1;
int j = right;
while(i <= j)
{
while(arr[pivot] > arr[i] && i <= right)
{
i++;
}
while(arr[pivot] < arr[j] && j >= left)
{
j--;
}
if(i <= j)
{
swap(arr,i,j);
}
else
{
swap(arr,pivot,j);
}
}
QuickSort(arr, left, j-1);
QuickSort(arr, j+1, right);
}
int main(int argc, const char * argv[]) {
int arr[] = {7,5,1,2,11,3,8,4,9};
int len = (sizeof(arr) / sizeof(int));
arr2 = new int[len];
//Bubble Sort
//BubbleSort(arr, len);
//Selection Sort
//SelectionSort(arr, len);
//Insertion Sort
//InsertionSort(arr, len);
//Merge Sort
//MergeSort(arr, len,0, len-1);
//Quick sort
//QuickSort(arr,0,len-1);
for(int i = 0 ; i < len ; i++)
{
cout << arr[i] << " ";
}
return 0;
}
|
cs |