您的位置:首页 > 其它

排序算法之冒泡排序

2016-10-29 22:45 176 查看
冒泡排序算法的核心思想是每一次循环,将最大的数放到最后,跟冒气泡一样。每一次比较相邻的前后二个数据,如果前面数据大于后面的数据,就将二个数据交换,这样对数组的第0个数据到N-1个数据进行一次遍历后,最大的一个数据就“沉”到数组第N-1个位置。依次循环,时间复杂度为O(n*n).代码如下:

#include<iostream>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-1-i; j++)
{
if (arr[j]>arr[j+1])
{
swap(arr[j], arr[j + 1]);

}

}

}
}
void printArray(int arr[], int n)
{
for (int  i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
int array[] = { 64, 25, 12, 22, 11 };
int n = sizeof(array) / sizeof(array[0]);
bubbleSort(array, n);
printArray(array, n);
return 0;
}

冒泡排序算法时间复杂度为O(n*n),如果排序过程中,如果元素已经排序好,已经排序好,可能还会排序下去。所以可以进行优化,设置一个标志,如果没有元素进行交换,那么停止即可。The above function always runs O(n^2) time even if the array is sorted.
It can be optimized by stopping the algorithm if inner loop didn’t cause any swap.

代码如下:

/ An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}

// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息