/**
* 冒泡排序
*
* 原理 是临近的数字两两进行比较,按照从小到大或者从大到小的顺序进行交换,
*
* 这样一趟过去后,最大或最小的数字被交换到了最后一位,
*
* 然后再从头开始进行两两比较交换,直到倒数第二位时结束
*
* @author daopinz
*
*/
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 6, 3, 8, 2, 9, 1, 4, 5 };
System.out.println("排序前的数组为:");
for (int num : arr) {
System.out.print(num + " ");
}
for (int i = 0; i < arr.length - 1; i++) {// 外层循环控制排序的趟数
for (int j = 0; j < arr.length - 1 - i; j++) {// 内层循环控制每一趟的排序的次数
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println();
System.out.println("排序后的数组为:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
输出:
排序前的数组为:
6 3 8 2 9 1 4 5
排序后的数组为:
1 2 3 4 5 6 8 9
/**
* 选择排序
*
* 原理:每一趟从待排序的记录中选出最小的元素,顺序放在已排好序的序列最后,直到全部记录排序完毕
* @author daopinz
*
*/
public class SelectionSort {
public static void main(String[] args) {
int[] arr={6, 3, 8, 2, 9, 1, 4, 5};
System.out.println("交换之前:");
for(int num : arr){
System.out.print(num+" ");
}
//选择排序的优化
for(int i=0;i<arr.length-1;i++){//做第i趟排序
int k=i;
for(int j=k+1;j<arr.length;j++){//选最小的记录
if(arr[j]>arr[k]){
k=j;//记下目前找到的最小值所在的位置
}
}
//在内层循环结束,也就是找到本轮循环的最小数以后,在进行交换
if(i!=k){//交换a[i]和a[k]
int temp=arr[i];
arr[i]=arr[k];
arr[k]=temp;
}
}
System.out.println();
System.out.println("交换后:");
for(int num : arr){
System.out.print(num+" ");
}
}
}
输出:
交换之前:
6 3 8 2 9 1 4 5
交换后:
9 8 6 5 4 3 2 1
/**
* 插入排序
*
* 原理 是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据
* @author daopinz
*
*/
public class SortArrs {
public static void main(String[] args) {
int[] x = { 6, 3, 8, 2, 9, 1, 4, 5 };
System.out.println("排序前:");
for(int s:x){
System.out.print(s+" ");
}
insert_sort(x);
}
public static void insert_sort(int[] unsorted) {
for (int i = 1; i < unsorted.length; i++) {
if (unsorted[i - 1] > unsorted[i]) {
int temp = unsorted[i];
int j = i;
while (j > 0 && unsorted[j - 1] > temp) {
unsorted[j] = unsorted[j - 1];
j--;
}
unsorted[j] = temp;
}
}
System.out.println();
System.out.println("排序后:");
for (int x:unsorted) {
System.out.print(x+" ");
}
}
}
输出:
排序前:
6 3 8 2 9 1 4 5
排序后:
1 2 3 4 5 6 8 9
总结:在大多情况下,假设当数据量比较小或者基本上有序时,插入排序算法是三种简单排序算法中最好的选择。对于更大数据量的排序来说,快速排序通常是最快的方法。
java排序算法:冒泡排序、选择排序、插入排序
最新推荐文章于 2025-05-30 00:50:08 发布