bubble sort optimization (#573)

This commit is contained in:
Du Yuanchao 2020-07-21 23:16:11 +08:00 committed by GitHub
parent 3dc947213a
commit e43024e8f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,20 +1,33 @@
// sorting of array list using bubble sort
/**
* @file
* @brief [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) algorithm
* implementation
*/
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*Displays the array, passed to this method*/
void display(int *arr, int n)
/**
* Display elements of array
* @param arr array to be display
* @param n length of array
*/
void display(const int *arr, int n)
{
int i;
for (i = 0; i < n; i++)
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
/*Swap function to swap two values*/
/**
* Swap two values by using pointer
* @param first first pointer of first number
* @param second second pointer of second number
*/
void swap(int *first, int *second)
{
int temp = *first;
@ -22,46 +35,61 @@ void swap(int *first, int *second)
*second = temp;
}
/*This is where the sorting of the array takes place
arr[] --- Array to be sorted
size --- Array Size
/**
* Bubble sort algorithm implementation
* @param arr array to be sorted
* @param size size of array
*/
void bubbleSort(int *arr, int size)
{
for (int i = 0; i < size - 1; i++)
{
{ /* for each array index */
bool swapped = false; /* flag to check if any changes had to be made */
/* perform iterations until no more changes were made or outer loop
executed for all array indices */
for (int j = 0; j < size - 1 - i; j++)
{
{ /* for each element in the array */
if (arr[j] > arr[j + 1])
{
{ /* if the order of successive elements needs update */
swap(&arr[j], &arr[j + 1]);
swapped = true; /* set flag */
}
}
if (!swapped)
{
/* since no more updates we made, the array is already sorted
this is an optimization for early termination */
break;
}
}
}
/**
* Test function
*/
void test()
{
const int size = 10;
int *arr = (int *)calloc(size, sizeof(int));
/* generate size random numbers from 0 to 100 */
for (int i = 0; i < size; i++)
{
arr[i] = rand() % 100;
}
bubbleSort(arr, size);
for (int i = 0; i < size - 1; ++i)
{
assert(arr[i] <= arr[i + 1]);
}
free(arr);
}
/** Driver Code */
int main(int argc, const char *argv[])
{
int n;
printf("Enter size of array:\n");
scanf("%d", &n); // E.g. 8
printf("Enter the elements of the array\n");
int i;
int *arr = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Original array: ");
display(arr, n); // Original array : 10 11 9 8 4 7 3 8
bubbleSort(arr, n);
printf("Sorted array: ");
display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11
free(arr);
/* Intializes random number generator */
srand(time(NULL));
test();
return 0;
}