java实现常用的排序算法1-冒泡和选择排序

 冒泡:

  冒泡的基本思想是对于无序的数据,嵌套循环比较大小,时间复杂度为 O(n^2);

package algorithm;


/**
* 冒泡排序,
*/
public class BubbleSort {

public static void main(String[] args) {
int[] arr = {7, 9, 2, 6, 0, 3, 8};
for (int i = 0; i < arr.length; i++) {//外层循环控制排序趟数
for (int j = i+1; j < arr.length; j++) {//内层循环控制每一趟排序多少次
if (arr[i] > arr[j]) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
for(int k :arr){
System.out.print(k+" ");
}
System.out.println("--");
}
for(int i :arr){
System.out.println(i);
}
}
}


选择排序:
和冒泡排序相比,将必要的交换次数从O(n^2)减少到O(n);选择排序中,不在只比较两个相邻的数据,需要记录下某一个指定的数据
  
public class SelectSort {

public static void selectionSort(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int k = i;
// 找出最小值的小标
for (int j = i + 1; j < n; j++) {
if (a[j] < a[k]) {
k = j;
}
}
// 将最小值放到排序序列末尾
if (k > i) {
int tmp = a[i];
a[i] = a[k];
a[k] = tmp;
}
for (int g : a){
System.out.print(g+ " ");}
System.out.println("------------");
}
}

public static void main(String[] args) {
int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 };
selectionSort(b);
for (int i : b)
System.out.print(i + " ");
}
}


  

猜你喜欢

转载自www.cnblogs.com/liwei2018/p/8955835.html