-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcode.cpp
More file actions
61 lines (56 loc) · 1.31 KB
/
code.cpp
File metadata and controls
61 lines (56 loc) · 1.31 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
#include <bits/stdc++.h>
using namespace std;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
//Bubble Sort is the simplest sorting algorithm that is works by repeatedly swapping the adjacent elements if they are in wrong order.
//complexcity: Worst complexity: n^2 //
//Average complexity: n^2//
//Best complexity: n//
//Space complexity: 1 //
// A function to implement in bubble sort
// bubble sort algorithm is very easy as compared to all sorting algorithms.
// The “bubble” sort is called so because the list elements with greater value than their surrounding an elements “bubble” towards the end of the list.
void bubbleSort(int arr[], int n)
{
int i, j,flag = 0;
for (i = 0; i < n-1; i++)
{
flag = 0;
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
flag = 1;
}
}
if(flag == 0)
{
break;
}
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
return 0;
}
// This code is contributed by shakti