Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 36 additions & 27 deletions sorting/bubble_sort.cpp
Original file line number Diff line number Diff line change
@@ -1,32 +1,41 @@
//complexity = O(n^2)
// C program for implementation of Bubble sort
#include <stdio.h>
int main()

void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int n;
scanf("%d",&n);
int arr[n];
int i;

for(i=0;i<n;i++){
scanf("%d",&arr[i]);
int i, j;
for (i = 0; i < n-1; i++)

// 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]);
}

int j,k,count=0;
for(j=0;j<n-1;j++){
for(k=0;k<n-j-1;k++){
if(arr[k]>arr[k+1]){
int temp,a;
temp=arr[k];
arr[k]=arr[k+1];
arr[k+1]=temp;
count++;
}
}

/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
for(i=0;i<n;i++){
printf("%d, ",arr[i]);

// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
printf("\nThe total number of swaps are %d\n",count);

return 0;
}