Java——数组排序
选择排序
public class Test01{
public static void main(String[] args){
int[] arr = {4,6,2,3,1,5};
for(int i = 0;i<arr.length;i++){
int current = arr[i];
int index = i;
for(int j = i+1 ;j<arr.length;j++){
if(arr[index] > arr[j]){
index = j;
}
}
arr[i] = arr[index];
arr[index] = current;
}
for(int i:arr){
System.out.println(i);
}
}
}
插入排序
public class Test02{
public static void main(String[] args){
int[] arr = {4,6,2,3,1,5};
for(int i = 0;i<arr.length-1;i++){
int current=[i+1];
int index = i;
while(index>=0 && current<arr[index]){
arr[index+1]=arr[index];
index--;
}
arr[index+1]=current;
}
for(int a:arr){
System.out.print(a+"\t");
}
}
}
冒泡排序
public class test03{
public static void main(String[] args){
int[] arr = {4,8,2,3,1,5};
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]){
arr[j]=arr[j]^arr[j+1];
arr[j+1] = arr[j]^arr[j+1];
arr[j] = arr[j]^arr[j+1];
}
}
}
for(int a:arr){
System.out.println(a);
}
}
}
二分查找
public class test04{
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int key = 9;
int start = 0;
int end = arr.length-1;
int mid = (start+end)/2;
while(end>=start){
if(arr[mid] == key){
System.out.println(mid);
break;
}else if(arr[mid] < key){
start = mid+1;
}else{
end = mid-1;
}
mid = (start+end)/2
}
if(end<start){
System.out.println("该数字不存在")
}
}
}
快速排序
public class Demo01 {
public static void main(String[] args) {
int[] arr = {3,7,6,1,8,2,0,9,-3,-1};
quictSort(arr,0,arr.length-1);
for (int i : arr) {
System.out.println(i);
}
}
public static void quictSort(int[] arr,int startIndex,int endIndex){
int current = arr[startIndex];
int low = startIndex;
int height = endIndex;
if (low>=height){
return;
}
while (low<height){
while(low < height && arr[height] > current){
height--;
}
while (low < height && arr[low] <= current){
low++;
}if (low<height){
int temp = arr[height];
arr[height] = arr[low];
arr[low] = temp;
}
}
arr[startIndex] = arr[height];
arr[height] = current;
quictSort(arr, startIndex, height-1);
quictSort(arr, height+1, endIndex);
}
}
随机排名
public class Test05{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int[] arr = new int[5];
for(int i = 0;i<arr.length;i++){
System.out.println("请输入第"+(i+1)+"员工编号:");
arr[i] = sc.nextInt();
int index = rand.nextInt(arr.length);
int temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
for(int a:arr){
System.out.println(a);
}
}
}
多维数组
定义二维数组
数据类型[][] 数组名;
数据类型 数组名[ ][ ];
// 动态初始化
int[][] arr = new int[3][4];
arr[0][0] = 1;
// 静态初始化
int[][] arr1 = new int[][]{
{1, 2, 3},
{2, 3},
{3, 4, 5, 4}
};
//二维数组的迭代
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
System.out.print(arr1[i][j]);
}
System.out.println();
}
for (int[] t : arr1) {
for (int a : t) {
System.out.println(a);
}
}