1、选择排序:
思路:选择排序(降序)每一轮循环都找到剩余数中最大的数放在当前轮数的首位,即选出最大值;
如第一轮 i = 0 时:该轮首位为 nums[0] ,然后从nums[1] 开始比较,每找到比nums[0] 大的数即交换数据,直到这轮结束。下一轮以nums[1] 为首位,从nums[2] 开始,直到结束。
升序排序反之即可。
选择排序{3,2,4,1}(降序) | |||
i j | 1 | 2 | 3 |
0 | {3,2,4,1} | {4,2,3,1} | — |
1 | {4,3,2,1} | — | — |
2 | — | — | — |
3 | — | — | — |
package com.planz;
public class SelectSort {
public static void main(String[] args){
int[] nums1 = orderBy(new int[]{3,2,4,1}, "desc");
for (int i = 0; i < nums1.length; i++) {
System.out.print(nums1[i]+" ");
}
System.out.println();
int[] nums2 = orderBy(new int[]{3,2,4,1}, "esc");
for (int i = 0; i < nums2.length; i++) {
System.out.print(nums2[i]+" ");
}
}
public static int[] orderBy(int[] nums,String type){
if (type.equalsIgnoreCase("desc")) {
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i]<nums[j]) {
int tem = nums[i];
nums[i] = nums[j];
nums[j] = tem;
}
}
}
}else if(type.equalsIgnoreCase("esc")){
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i]>nums[j]) {
int tem = nums[i];
nums[i] = nums[j];
nums[j] = tem;
}
}
}
}
return nums;
}
}
2、冒泡排序:
思路:(1)冒泡排序分两个数据域,一个无序区,每次需要遍历比较,每轮递减,一个有序区,每轮递增,在数组末尾;
(2)冒泡排序默认为升序排序,小的数像气泡一样上浮(左移),大的数像石头一样下沉(右移);
(3)外层循环轮数为n-1 ,内层遍历个数为无序区;
冒泡排序{3,2,4,1}(升序) | |||
i j | 0 | 1 | 2 |
0 | {2,3,4,1} | {2,3,4,1} | {2,3,1,4} |
1 | {2,3,1,4} | {2,1,3,4} | |
2 | {1,2,3,4} |
package com.planz;
public class BubbleSort {
public static void main(String[] args){
int[] nums = orderBy(new int[]{3,2,4,1});
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
}
public static int[] orderBy(int[] nums){
for (int i = 0; i < nums.length-1; i++) {//循环论数(n-1)次循环即可
for (int j = 0; j < nums.length-1-i; j++) {//无序区的遍历,剩余的为已排好的有序区
if (nums[j]>nums[j+1]) {//小的数上浮
int tem = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tem;
}
}
}
return nums;
}
}
此外还有快速排序、直接插入排序、二分法、使用Array.sort(int[] array)等等,在此暂时不赘述了,嘻嘻....