Bubble Sort 2 Algorithm
Bubble Sort 2 Algorithm, also known as the Bidirectional Bubble Sort or Cocktail Sort, is a variation of the traditional Bubble Sort algorithm that efficiently sorts a list of items by comparing and swapping adjacent elements. The primary difference between the two sorting techniques lies in the manner in which they traverse the list. While the original Bubble Sort algorithm only moves in a single direction (from the beginning to the end of the list), the Bubble Sort 2 Algorithm traverses the list in both directions, making it a more efficient sorting technique. This bidirectional approach helps in reducing the number of iterations, as it can move smaller and larger elements to their correct positions in a single pass.
The Bubble Sort 2 Algorithm begins by comparing and swapping elements from the start of the list to the end, just like the traditional Bubble Sort. However, once it reaches the end of the list, it changes direction and starts comparing and swapping elements from the end of the list back to the beginning. By moving through the list in both directions, Bubble Sort 2 can identify and position both the smallest and largest elements in the list during a single pass. This alternating traversal continues until the entire list is sorted. Despite being more efficient than the original Bubble Sort, Bubble Sort 2 still has a worst-case and average-case time complexity of O(n^2), making it inefficient for sorting large lists compared to other sorting algorithms like Quick Sort or Merge Sort.
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
#define TRUE 1
#define FALSE 0
int main()
{
int i , arraySort[MAX] ={0} , isSort = FALSE, changePlace;
/* For example
Insertion random values in array to test
*/
for(i = 0 ; i < MAX; i++)
{
arraySort[i] = rand()%101 ;
}
/* Algorithm of bubble methods */
while(isSort)
{
isSort = FALSE;
for( i = 0 ; i < MAX - 1 ; i++)
{
if(arraySort[i] > arraySort[i+1])
{
changePlace = arraySort[i];
arraySort[i] = arraySort[i+1];
arraySort[i+1] = changePlace ;
isSort = TRUE;
}
}
}
/* See if it works */
for(i = 0 ; i < MAX; i++)
{
printf("%d\n", arraySort[i]);
}
return EXIT_SUCCESS;
}