1.冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//冒泡排序
public static int [] bubbleSort(int arr []){
int n = arr.length;
for(int i = 0; i < n-1; i++){
for (int j = 0; j< n -i -1; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}

public static void main(String[] args) {
int [] arrays = {1,6, 9 ,4,2,3};
int[] sortArrays = bubbleSort(arrays);
System.out.println(Arrays.toString(sortArrays));
}

2.选择排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 选择排序
public static int [] selectSort(int arr[]){
int n = arr.length;

for(int i = 0; i<n - 1; i++){
int minIndex = i;
for(int j = i+1; j< n; j++){
if(arr[j]<arr[minIndex]){
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
public static void main(String[] args) {
int [] arrays = { 1, 3, 6,4,7,12,5,1,2};
int[] arraysSort = selectSort(arrays);
System.out.println(Arrays.toString(arraysSort));
}

3.插入排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 插入排序
public static int [] insertSort (int [] arr){
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i-1;
while (j>=0 && arr[j]> key){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
return arr;
}

public static void main(String[] args) {
int [] arrays = {2,5,3,9,4,1};
int[] arraysSort= insertSort(arrays);
System.out.println(Arrays.toString(arraysSort));
}

4.两数之和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 两数之和
public static Integer [] twoSum(Integer[] nums , Integer target){
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])){
return new Integer[] {map.get(target - nums[i]),i};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException( "");
}
public static void main(String[] args) {
Integer [] arr = {2,7,11,15};
Integer target = 17;
Integer[] index = twoSum(arr, target);
System.out.println(Arrays.toString(index));
}

5.回文数