C++ 程序实现冒泡排序
冒泡排序是一种基于比较的排序算法。在该算法中,将相邻元素进行比较和交换,以形成正确的序列。该算法比其他算法更简单,但也存在一些缺点。该算法不适用于海量数据集。它需要花费大量时间来解决排序任务。
冒泡排序技术的复杂度
时间复杂度:最好情况 O(n),平均情况和最坏情况 O(n2)
空间复杂度: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(数组,大小)
输入:数据数组和数组中的总数
输出:排序后的数组
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
广告