java---数字排序
生活随笔
收集整理的這篇文章主要介紹了
java---数字排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java中利用數組進行數字排序一般有4種方法:選擇排序法、冒泡法、快速排序法、插入排序法。
選擇排序是先將數組中的第一個數作為最大或最小數,然后通過循環比較交換最大數或最小數與一輪比較中第一個數位置進行排序;
冒泡排序也是先將數組中的第一個數作為最大或最小數,循環比較相鄰兩個數的大小,滿足條件就互換位置,將最大數或最小數沉底;
快速排序法主要是運用Arrays類中的Arrays.sort方法()實現。
插入排序是選擇一個數組中的數據,通過不斷的插入比較最后進行排序。
選擇排序法
package com.lovo;public class Test01 {public static void main(String[] args) {int[] a = new int[5];for(int i = 0; i < a.length; i++) {a[i] = (int) (Math.random() * 99 + 1);System.out.print(a[i] + " ");}// 簡單選擇排序for(int i = 0; i < a.length - 1; i++) {int minIndex = i;for(int j = i + 1; j < a.length; j++) {if(a[j] < a[minIndex]) {minIndex = j;}}if(minIndex != i) {int temp = a[i];a[i] = a[minIndex];a[minIndex] = temp;}}for(int x : a) {System.out.print(x + " ");}} }?
冒泡排序法
package com.lovo;public class Test02 {public static void main(String[] args) {int[] a = new int[5];for(int i = 0; i < a.length; i++) {a[i] = (int) (Math.random() * 99 + 1);System.out.print(a[i] + " ");}// 冒泡排序boolean swapped = true; // 有沒有發生過交換for(int i = 1; swapped && i <= a.length - 1; i++) {swapped = false; for(int j = 0; j < a.length - i; j++) {if(a[j] > a[j + 1]) {int temp = a[j];a[j] = a[j + 1];a[j + 1] = temp;swapped = true;}}}for(int x : a) {System.out.print(x + " ");}} }?
快速排序法
package com.lovo;import java.util.Arrays;public class Test03 {// 快速排序法public static void main(String[] args) {int[] a = new int[5];System.out.print("排序前: ");for (int i = 0; i < a.length; i++) {a[i] = (int) (Math.random() * 99 + 1);System.out.print(a[i] + " ");}System.out.print("\n排序后:");Arrays.sort(a); // 進行排序for (int x : a) {System.out.print(x + " ");}} }?
轉載于:https://www.cnblogs.com/iguo/p/4051704.html
總結
以上是生活随笔為你收集整理的java---数字排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于K-Meleon浏览器的使用技巧汇总
- 下一篇: Robot Framework--06