java中的数组
数组的初始化大致有三种写法,一种动态初始化和两种静态初始化。
动态初始化:
int[] a = new int[length]; //length必须指定且为正整数
静态初始化:
int[] a = new int[]{1,2,3,4};
int[] a = {1,2,3,4};
对数组的循环有fori和foreach两种写法
java中的排序
选择排序
public static void sort (int[] arr){
for (int i = 0; i < arr.length; i++) {
int min = i;
int temp = arr[i];
for (int j = i+1; j < arr.length; j++) {
if (arr[min] > arr[j]) min = j;
}
arr[i] = arr[min];
arr[min] = temp;
}
}
冒泡排序
public static void sort (int[] arr){
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length-1-i; j++) {
if (arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
插入排序
public static void sort(int[] arr){
for(int i = 1; i < arr.length; i++) {
for(int j = i; j > 0 && arr[j-1] > arr[j]; j--) {
int tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
}
}
快速排序
public static void sort(int[] arr){
sort(arr,0,arr.length-1);
}
private static void sort(int[] arr ,int left ,int right){
if (left > right) return;
int i = left;
int j = right;
int mid = arr[left];
while (i != j){
while (arr[j] >= mid && i < j){
j--;
}
while (arr[i] <= mid && i < j){
i++;
}
if (i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[left] = arr[i];
arr[i] = mid;
sort(arr, left, i-1);
sort(arr, i+1, right);
}
归并排序
public static void sort(int[] arr) {
merge_sort_recursive(arr, new int[arr.length], 0, arr.length - 1);
}
private static void merge_sort_recursive(int[] arr, int[] result, int start, int end) {
if (start >= end)
return;
int len = end - start, mid = (len >> 1) + start;
int start1 = start, end1 = mid;
int start2 = mid + 1, end2 = end;
merge_sort_recursive(arr, result, start1, end1);
merge_sort_recursive(arr, result, start2, end2);
int k = start;
while (start1 <= end1 && start2 <= end2)
result[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++];
while (start1 <= end1)
result[k++] = arr[start1++];
while (start2 <= end2)
result[k++] = arr[start2++];
for (k = start; k <= end; k++)
arr[k] = result[k];
}
希尔排序
public static void sort (int[] arr){
int length = arr.length/2;
while (length >= 1){
for (int i = length; i < arr.length; i++) {
int temp = arr[i];
int j = i - length;
while (j >= 0 && arr[j] > temp){
arr[j + length] = arr[j];
j = j -length;
}
arr[j + length] = temp;
}
length = length/2;
}
}