class array
{
public static void main (String[] args) {
int[] arr = {2,3,8,9,7,1,20};
/* System.out.println(max(arr));*/
/* selectSort_2(arr); */
/* bubbleSort(arr); */
selectSort_2(arr);
print_r(arr);
}
static void print_r(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
static int max (int[] arr) {
int max = 0;
for (int i = 0; i < arr.length; i++) {
max = max > arr[i] ? max : arr[i];
}
return max;
}
static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
/*
1.{3,2,8,10}
2.{8,2,3,10}
3.{10,2,3,8}
1.{10,3,2,8}
2.{10,8,2,3}
1.{10,8,3,2}
*/
static void selectSort(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] < arr[j]) {
swap(arr, i, j);
}
}
}
}
static void selectSort_2(int[] arr) {
int num, index;
for (int i = 0; i < arr.length - 1; i++) {
num = arr[i];
index = i;
for (int j = i + 1; j< arr.length; j++) {
if (arr[j] > num) {
num = arr[j];
index = j;
}
}
swap(arr, i,index);
}
}
/*
1.{3,2,8,10}
2.{3,8,2,10}
3.{3,8,10,2}
1.{8,3,10,2}
2.{8,10,3,2}
1.{10,8,3,2}
*/
static void bubbleSort(int[] arr) {
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]) {
swap(arr, j, j+1);
}
}
}
}
}
java版选择排序和冒泡排序
最新推荐文章于 2023-10-03 11:53:44 发布