代码如下:
package com.stu.demo;
import javax.naming.ldap.SortControl;
/**
*
* @author ysw28 数组排序
*/
public class Demo01 {
public static void main(String args[]) {
// 定义一个数组
int date[] = new int[] { 2, 0, 3, 5, 8, 9, 6, 1, 4, 7 };
System.out.println("排序前:");
print(date);
System.out.println();
System.out.println("排序后:");
sort(date);
print(date);
}
// 定义一个排序方法
public static void sort(int date[]) {
// 定义排序的次数,绝对不会大于数组的长度
for (int i = 0; i < date.length; i++) {
//控制每次的排序
for (int j = 0; j < date.length - 1; j++) {
if (date[j] > date[j + 1]) {
int t = date[j];
date[j] = date[j + 1];
date[j + 1] = t;
}
}
}
}
// 定义一个输出数组的方法
public static void print(int temp[]) {
for (int i = 0; i < temp.length; i++) {
System.out.print(temp[i] + ",");
}
}
}
```
数组的排序(升序)可以使用Java.util.Arrays.sort();这个方法
package com.stu.demo;
/**
*
* @author ysw28
* 数组倒置
*/
public class Demo02 {
public static void main(String[] args) {
int date[] = new int[]{1,2,3,4,5,6,7,8};
reverse(date);
print(date);
}
//定义一个倒置数组的方法
public static void reverse(int arr[]){
int len = arr.length/2;//数组转换次数
int head = 0;//头部索引
int tail = arr.length-1;//尾部索引
for (int i = 0; i < len; i++) {
int t = arr[head];
arr[head] = arr[tail];
arr[tail] = t;
head++; //头部索引增加
tail--; //尾部索引减少
}
}
//定义一个输出数组的方法
public static void print(int temp[]) {
for(int i = 0; i<temp.length;i++) {
System.out.print(temp[i]+",");
}
}
}