Computer >> 컴퓨터 >  >> 프로그램 작성 >> 프로그램 작성

버블 정렬


버블 정렬은 비교 기반 정렬 알고리즘입니다. 이 알고리즘에서는 인접한 요소를 비교하고 교환하여 올바른 순서를 만듭니다. 이 알고리즘은 다른 알고리즘보다 간단하지만 몇 가지 단점도 있습니다. 이 알고리즘은 많은 수의 데이터 세트에 적합하지 않습니다. 정렬 작업을 해결하는 데 시간이 많이 걸립니다.

버블 정렬 기법의 복잡성

  • 시간 복잡성: 최상의 경우 O(n), 평균 및 최악의 경우 O(n^2)
  • 공간 복잡성: O(1)

입력 및 출력

Input:
A list of unsorted data: 56 98 78 12 30 51
Output:
Array after Sorting: 12 30 51 56 78 98

알고리즘

bubbleSort( array, size)

입력 - 데이터 배열 및 배열의 ​​총 개수

출력 - 정렬된 배열

Begin
   for i := 0 to size-1 do
      flag := 0;
      for j:= 0 to size –i – 1 do
         if array[j] > array[j+1] then
            swap array[j] with array[j+1]
            flag := 1
      done

      if flag ≠ 1 then
         break the loop.
   done
End

예시

#include<iostream>
using namespace std;

void swapping(int &a, int &b) { //swap the content of a and b
   int temp;
   temp = a;
   a = b;
   b = temp;
}

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void bubbleSort(int *array, int size) {
   for(int i = 0; i<size; i++) {
      int swaps = 0; //flag to detect any swap is there or not
      for(int j = 0; j<size-i-1; j++) {
         if(array[j] > array[j+1]) { //when the current item is bigger than next
            swapping(array[j], array[j+1]);
            swaps = 1; //set swap flag
         }
      }
      if(!swaps)
         break; // No swap in this pass, so array is sorted
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   bubbleSort(arr, n);

   cout << "Array after Sorting: ";
   display(arr, n);
}

출력

Enter the number of elements: 6
Enter elements:
56 98 78 12 30 51
Array before Sorting: 56 98 78 12 30 51
Array after Sorting: 12 30 51 56 78 98