Bubble sort implementation of C language sorting algorithm [modified version]
- 2020-05-30 20:35:06
- OfStack
This paper illustrates the bubble sort implementation of C language sorting algorithm. I will share it with you for your reference as follows:
Bubble sort and improved bubble sort
/*-------------------------------------------------------------------------------------------
Bubble_sort.h
Bubble sort: The time complexity is O(N^2)
Improved bubble sort: The time complexity is still zero O(N^2)
1 It is possible that the bubble sort method will continue to compare and improve the bubble sort even though the order has already been sorted
Set up 1 A sentry flag If the 1 time for If the loop is not swapped, the elements are sorted and exit the loop under sentry control.
-------------------------------------------------------------------------------------------*/
#ifndef BUBBLE_SORT_H
#define BUBBLE_SORT_H
#include "typedef.h"
#include "swap.h"
// Bubble sort
void Bubble_sort(T *a, int n)
{
for(int i=n-1; i != 0; --i)
for(int j=0; j != i; ++j)
if(a[j+1] < a[j]) swap(a[j+1],a[j]);
}
// Improved bubble sort
void Improved_Bubble_sort(T *a, int n)
{
for(int i=n-1; i != 0; --i)
{
bool flag = true;
for(int j=0; j != i; ++j) // this 1 If the traversal is not swapped, the sorting is completed
if(a[j+1] < a[j]) { swap(a[j+1],a[j]); flag = false; }
if(flag == true) break;
}
}
#endif
I hope this article has been helpful to you in programming the C language.