-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubble-Sort.cpp
58 lines (42 loc) · 1.08 KB
/
Bubble-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
#include <iostream>
void Bubble_Sort(int arr[], int n);
void opt_Bubble_Sort(int arr[], int n);
void swap(int* a, int* b);
int main(){
int arr[50], n;
std::cout<< "Enter the size of your array : " ;
std::cin >> n;
std::cout<< "Enter the elements of your array : " ;
for(int i=0; i<n; ++i)
std::cin >>arr[i];
opt_Bubble_Sort(arr,n);
std::cout<< "Sorted array : " << std::endl;
for(int i=0; i<n; ++i)
std::cout << arr[i] << ",";
return 0;
}
void Bubble_Sort(int arr[], int n){
for (int i=0; i<n; ++i)
for (int j=0; j<n-1-i; ++j)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
void opt_Bubble_Sort(int arr[], int n){
for (int i=0; i<n; ++i){
bool swapped = false;
for(int j=0; j<n-i; ++j){
if(arr[j] > arr[j+1]){
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}
void swap(int* a, int* b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}