学习JAVA第二十四天
2021/8/26 9:06:14
本文主要是介绍学习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;
}
}
这篇关于学习JAVA第二十四天的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-27消息中间件底层原理资料详解
- 2024-11-27RocketMQ底层原理资料详解:新手入门教程
- 2024-11-27MQ底层原理资料详解:新手入门教程
- 2024-11-27MQ项目开发资料入门教程
- 2024-11-27RocketMQ源码资料详解:新手入门教程
- 2024-11-27本地多文件上传简易教程
- 2024-11-26消息中间件源码剖析教程
- 2024-11-26JAVA语音识别项目资料的收集与应用
- 2024-11-26Java语音识别项目资料:入门级教程与实战指南
- 2024-11-26SpringAI:Java 开发的智能新利器