数组排序
冒泡排序: 从0索引开始,依次和后面元素比较 大的往后放,经过比较后,最大得元素会出现在最大索引处。
public class demo1
{
public
static void main(String
[] args
) {
int[] arr
= {24, 69, 80, 57, 13};
for (int j
= 0; j
< arr
.length
-1; j
++) {
for (int i
= 0; i
< arr
.length
-1-j
; i
++) {
if (arr
[i
] > arr
[i
+ 1]) {
int t
= arr
[i
];
arr
[i
] = arr
[i
+ 1];
arr
[i
+ 1] = t
;
}
}
}
System
.out
.println(Arrays
.toString(arr
));
}
}
选择排序: 从0索引开始,依次和后面元素比较 小的往前放,经过比较后,最小值出现在了最小索引处。
public class demo2
{
public
static void main(String
[] args
) {
int[] arr
= {9, 1, 0, 4, 3, 5, 7, 6, 8, 11, 10, -1, 100};
for (int i
= 0; i
< arr
.length
- 1; i
++) {
for (int j
= 1 + i
; j
< arr
.length
; j
++) {
if (arr
[i
] > arr
[j
]) {
int t
= arr
[i
];
arr
[i
] = arr
[j
];
arr
[j
] = t
;
}
}
}
System
.out
.println(Arrays
.toString(arr
));
}
}
插入排序:每次将后面一个元素,插入到之前得一个有序序列中,使之仍保持有序
import java
.util
.Arrays
;
public class demo3
{
public
static void main(String
[] args
) {
int[] arr
= {9, 1, 0, 15, 165, 61, 81, 100, 32};
for (int i
= 1; i
< arr
.length
; i
++) {
for (int j
= i
; j
> 0; j
--) {
if(arr
[j
]<arr
[j
-1]){
int t
= arr
[j
];
arr
[j
] = arr
[j
- 1];
arr
[j
- 1] = t
;
}
}
}
System
.out
.println(Arrays
.toString(arr
));
}
}
一般情况查找索引
public
static void main(String
[] args
) {
int[] arr
= {11, 84, 31, 94, 28, 59, 78, 69, 15};
int index
= GetIndex(arr
, 28);
System
.out
.println("索引为:"+index
);
}
private
static int GetIndex(int[] arr
, int yuansu
) {
int h
= -1;
for (int i
= 0; i
< arr
.length
; i
++) {
if (arr
[i
] == yuansu
) {
h
= i
;
break;
}
}
return h
;
}
二分查找
前提:数组必须有序
import java
.util
.Arrays
;
public class demo2
{
public
static void main(String
[] args
) {
int[] arr
= {15, 94, 31, 74, 62, 2, 36};
Arrays
.sort(arr
);
System
.out
.println(Arrays
.toString(arr
));
int index
= getIndex(arr
,74);
System
.out
.println("74元素的索引为:"+index
);
}
private
static int getIndex(int[] arr
, int yuansu
) {
int min
= 0;
int max
= arr
.length
- 1;
int center
= (max
+ min
) / 2;
while (min
<= max
) {
if (yuansu
> arr
[center
]) {
min
= center
+ 1;
} else if (yuansu
< arr
[center
]) {
max
= center
- 1;
} else {
return center
;
}
center
= (min
+ max
) / 2;
}
return -1;
}
}
转载请注明原文地址: https://mac.8miu.com/read-498595.html