Java進階(二)-陣列中常見的演算法
阿新 • • 發佈:2022-03-03
陣列中涉及的常見演算法
1. 陣列元素的賦值(楊輝三角、回形數等)
//使用二維陣列列印一個10行的楊輝三角 //1.第一行有1個元素,第n行有n個元素 //2.每一行的第一個元素和最後一個元素都是1 //3.從第三行開始,對於非第一個元素和最後一個元素的元素,滿足: //yanghui[i][j]=yanghui[i-1][j-1]+yanghui[i-1][j]; public class YangHuiTest { public static void main(String[] args) { //1.宣告並初始化二維陣列 int[][] yanghui=new int[10][]; //2.給陣列賦值 for (int i = 0; i < yanghui.length; i++) { yanghui[i]=new int[i+1]; //每一行有多少個元素 //2.1給首末元素賦值 yanghui[i][0]=1; yanghui[i][i]=1; //2.2給每行非首末元素賦值 if(i>1){ for (int j = 1; j <yanghui[i].length-1 ; j++) { yanghui[i][j]=yanghui[i-1][j-1]+yanghui[i-1][j]; } } } //3.遍歷二維陣列 for (int i = 0; i < yanghui.length; i++) { for (int j = 0; j < yanghui[i].length; j++) { System.out.print(yanghui[i][j]+" "); } System.out.print("\n"); } } }
2.求數值型陣列中元素的最大值、最小值、平均數、總數
3.陣列的複製、反轉、查詢(線性查詢、二分法查詢)
//陣列的複製 public class Copy { public static void main(String[] args) { //賦值array2等於array1,不能稱作陣列的複製 int[] array1; int[] array2; array1=new int[]{1,3,4,5,6}; array2=new int[array1.length]; for (int i = 0; i < array2.length; i++) { array2[i]=array1[i]; } for (int i = 0; i < array2.length; i++) { System.out.print(array2[i]+" "); } }
//陣列反轉 public class Reverse { public static void main(String[] args) { int[] array={1,3,4,5,6,7,4,3}; //陣列反轉 for (int i = 0,j=array.length-1; i <j ; i++,j--) { int temp=array[i]; array[i]=array[j]; array[j]=temp; } //遍歷 for (int i = 0; i < array.length; i++) { System.out.print(array[i]+" "); } } }
//線性查詢
public class LinearLook {
public static void main(String[] args) {
int[] array={1,3,4,5,6,7,4,3};
//線性查詢
int dest=8;
boolean isFlag=true;
for (int i = 0; i < array.length; i++) {
if(array[i]==dest){
System.out.println(i);
isFlag=false;
break;
}
}
if(isFlag){
System.out.println("沒有找到");
}
}
}
public class Binary {
public static void main(String[] args) {
int[] array1={1,3,43,5,6,8,19,4,9};
//{1,3,4,5,6,8,9,19,43}
Arrays.sort(array1);
//二分法查詢,前提是所要查詢的陣列必須有序
int dest=43;
int head=0;//初始首索引
int end=array1.length-1;
boolean isFlag=true;
while(head<=end){
int middle=(end+head)/2;
if(dest==array1[middle]){
System.out.println("找到了指定元素:"+middle);
isFlag=false;
break;
}else if(dest>array1[middle]){
head=middle+1;
}else{
end=middle-1;
}
}
if(isFlag){
System.out.println("沒找到");
}
}
}
4.陣列元素的排序演算法
-
十大內部排序演算法(主要是前面八種)
關於排序演算法資料結構裡邊的排序演算法講的比較詳細!還附有相應的程式碼
- 選擇排序(直接選擇排序、堆排序)
- 交換排序(氣泡排序、快速排序)
- 插入排序(直接插入排序、折半插入排序、Shell希爾排序)
- 歸併排序
- 桶式排序
- 基數排序
//氣泡排序
public class BubbleSort {
public static void main(String[] args) {
int[] arr=new int[]{2,3,4,5,6,2,1,9,0,8};
//外層決定迴圈的次數
for (int i = 0; i < arr.length-1; i++) {
//內層決定怎麼排序
for (int j = 0; j < arr.length-1-i; j++) {
int temp=0;
if(arr[j+1]<arr[j]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
}