一、冒泡排序
public static void main(String[] args) {
int[] a = {2, 4, 1, 4, 3, 7, 5, 6, 9};
//冒泡排序
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length-1-i; j++) {
if (a[j+1] > a[j]) {
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
}
二、选择排序
public static void main(String[] args) {
//选择排序
int[] a = {2, 4, 1, 4, 3, 7, 5, 6, 9};
for (int i = 0; i < a.length-1; i++){
for (int j = i+1; j < a.length; j++ ){
if(a[j] > a[i]){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+"\t");
}
}
三、JDK排序(只能升序)
public static void main(String[] args) {
//JDK排序 只能升序
int[] a = {2, 4, 1, 4, 3, 7, 5, 6, 9};
java.util.Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+"\t");
}
}
四、二分法查找
public static void main(String[] args) {
//二分法查找 (在数组已经排好序的情况下)
int[] a = {1,3,4,5,7,8,9};
System.out.println(search(a, 3, 0, a.length - 1));
}
public static int search(int a[],int n,int start,int end){
if(start>end) return -1; //表示没有找到
int middle = (start+end)/2;
int value = a[middle];
if(value < n) //表示要找的数位于数组中间位置的右边
return search(a,n,middle+1,end);
else if (value > n) //表示要找的数位于数组中间位置的左边
return search(a,n,start,middle-1);
else
return middle; //表示要找的数就是数组中间位置的值
}
五、查重算法
public static void main(String[] args) {
//查重算法
int[] a = {6,2,1,4,7,2,6,4,1};
int result = 0 ;
for (int i = 0; i < a.length; i++) {
result ^= a[i]; //异或满足交换律,相同的抵消,单独的值最后赋值给result
}
System.out.println(result);
}
六、桶排序
· 使用场景单一:数组里的数不超过20且是整数。使用场景单一。
public static void main(String[] args) {
//桶排序
int[] a = {1,4,3,2,7,6,9,8,2,5};
int b[] = new int[21];
for (int i = 0; i < a.length; i++) {
b[a[i]]++; //b数组的下标是a数组中元素,b数组的值是每个对应a数组元素出现的次数。
}
for (int i = 0; i < b.length; i++){
for (int j = 1;j <= b[i];j++){
System.out.print(i+"\t");
}
}
}
本文深入探讨了多种排序算法,包括冒泡排序、选择排序、JDK内置排序,以及二分法查找和桶排序等高级搜索算法。同时,介绍了查重算法的实现,为数据处理提供了实用技巧。
5万+

被折叠的 条评论
为什么被折叠?



