Monday, August 31, 2020

Write a Program of Bubble sort in C.

  • This is the most common technique used in extreme use. In this, compare the first value of any Array to the second value of Array. 
  • If the second value of Array is greater than the first value, then the second data is placed in the first place and the first place's data in the second place to be arranged in ascending order. 
  • Then compare the second value of Array to the third value and if the third value is larger than the second value, then the third value is replaced by the second value and the third value instead of the second value.
  • If the second value is not greater than the third value then no change is made in the location of the second and third values ​​of the Array.

Bubble Sort Algorithm

bubbleSort(arr)
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
end bubbleSort

Optimized Bubble Sort

bubbleSort(array)
  swapped <- false
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
      swapped <- true
end bubbleSort


EXAMPLE :-


#include <stdio.h>
void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
int main()
{
int arr[] = {65, 35, 25, 50, 12, 61, 70};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array..... \n");
printArray(arr, n);
return 0;
}


OUTPUT


Sorted array..... 12 25 35 50 61 65 70






No comments:

Post a Comment

Please do not any spam link in Comment Box