校招算法复习之冒泡排序

来源:互联网 发布:matlab定义空矩阵 编辑:程序博客网 时间:2024/06/05 22:45

      冒泡排序是指对一串数字进行排序,其中形象的表示是指这个算法的名字由来是因为越大的元素会经由交换慢慢“浮”到数列的顶端,故名。就是说最原始的冒泡排序是指从小到大排序(当然排序从小到大还是从大到小都没有关系啦~)

      算法思想(Bubble sort):按从小到大排序。把数字按输入顺序从左到右排成一列(在内存中一般用数组实现)。然后从左到右依次去比较找寻当前最小值。比如vector[0]是最小的数字,而vector[1]是除vector[0]的最小值。而找寻的过程是遍历和交换。

     

#include<iostream>using namespace std;void bubbleSort(int* bubble,int num);int main(){int num;//输入排序数组大小cout << "please inputh the num:" ;cin >> num;cout << endl;int * bubble = new int[num];cout << "please input the integers:" << endl;for (int i = 0; i < num; i++)cin >> bubble[i];bubbleSort(*&bubble,num);for (int i = 0; i < num; i++){cout << bubble[i] << endl;}system("pause");delete[]bubble;return 0;}void bubbleSort(int* bubble,int num){int swap_value = 0;int temp = 0;for (int i = 0; i < num; i++)for (int j = 0; j < num - i-1; j++){if (bubble[j]>bubble[j + 1]){temp = bubble[j];bubble[j] = bubble[j + 1];bubble[j + 1] = temp;}}}

      从代码中可以看出冒泡排序的算法复杂度是O(n2)。而且算法是稳定的。但是此时的复杂度不管哪种情况都是O(n2)。


     java代码实现:

package music_store;import java.util.Scanner;import java.util.function.IntPredicate;import android.R.integer;public class bubbleSort {public static void bubbleSort(int[] bubble){int length=bubble.length;int temp=0;for(int i=0;i<length;i++)for(int j=0;j<length-i-1;j++){if(bubble[j]>bubble[j+1]){temp=bubble[j];bubble[j]=bubble[j+1];bubble[j+1]=temp;}}}public static void main(String[]args){Scanner inScanner=new Scanner(System.in);int n=inScanner.nextInt();int[] bubble=new int[n];for(int i=0;i<n;i++){bubble[i]=inScanner.nextInt();}bubbleSort(bubble);//System.out.println(bubble);   for(int num:bubble)   {   System.out.println(num);      }}}


1 0
原创粉丝点击