学习JAVA第二十四天
作者:互联网
java冒泡排序
public class BubbleSort {
public static void main(String[] args) {
int a[] = { 2, 3, 6, 4, 0, 1, 7, 8, 5, 9 };
bubbleSort(a);
}
public static void toString(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
private static void bubbleSort(int[] a) {
int length = a.length;
int temp = 0;
for (int j = 0; j < a.length - 1; j++) {
for (int i = 0; i < a.length - 1 - j; i++) {
if (a[i] > a[i + 1]) {
temp = a[i + 1];
a[i + 1] = a[i];
a[i] = temp;
}
}
}
toString(a);
}
}
2.java选择排序
public class SortDemo { public static void main(String[] args) { int[] arr = new int[] { 5, 3, 6, 2, 10, 2, 1 }; selectSort(arr); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void selectSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int minIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } if (i != minIndex) { int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } } } 3.java插入排序 public class CRPX {public static void main(String[] s) {
int[] a = {1,2,3,0};
insertSort(a,0,a.length);
for(int n : a){
System.out.print(n+" ");
}
}
public static void insertSort(int[] object,int low,int high) {
for(int i = 1;i<high;i++) {
if(object[i] < object[i-1]) {
int temp = object[i];
int j = i-1;
for(;j >=low&&object[j] > temp;j--) {
object[j+1] = object[j];
}
object[j+1] = temp;
}
}
}
} 4.java快速排序 package quickSort;
public class QuickSort {
private static int count;
public static void main(String[] args) {
int[] num = {7,4,1,8,5,2,9,6,3,10};
System.out.println(arrayToString(num,"未排序"));
QuickSort(num,0,num.length-1);
System.out.println(arrayToString(num,"排序"));
System.out.println("数组个数:"+num.length);
System.out.println("循环次数:"+count);
}
private static void QuickSort(int[] num, int left, int right) {
if(left>=right) {
return;
}
int key=num[left];
int i=left;
int j=right;
while(i<j){
while(num[j]>=key && i<j){
j--;
}
while(num[i]<=key && i<j){
i++;
}
if(i<j){
int temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
num[left]=num[i];
num[i]=key;
count++;
QuickSort(num,left,i-1);
QuickSort(num,i+1,right);
}
private static String arrayToString(int[] arr,String flag) {
String str = "数组为("+flag+"):";
for(int a : arr)
str += a + "\t";
}
return str;
}
}
标签:arr,JAVA,int,学习,length,num,第二十四,static,public 来源: https://www.cnblogs.com/wangao666/p/15187768.html