发布网友 发布时间:2022-03-30 03:34
共2个回答
热心网友 时间:2022-03-30 05:03
public class TestBaiKnow {
public static void main(String[] args) {
int[] a = { 3, 5, 6, 1, 2, 8, 9 };
// 冒泡 排序后结果从小到大
for (int i = 0; i < a.length; i++)
for (int j = i; j < a.length; j++) {
if (a[i] > a[j]) {
a[i] = a[i] + a[j];
a[j] = a[i] - a[j];
a[i] = a[i] - a[j];
}
}
print(a);
// 选择排序 结果从大到小
int pos = -1;
for (int i = 0; i < a.length; i++) {
int max = a[i];
for (int j = i + 1; j < a.length; j++) {
if (max < a[j]) {
pos = j;
max = a[j];
}
}
if (pos != -1) {
a[i] = a[i] + a[pos];
a[pos] = a[i] - a[pos];
a[i] = a[i] - a[pos];
pos = -1;
}
}
print(a);
}
private static void print(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + "\t");
System.out.println();
}
}
热心网友 时间:2022-03-30 06:21
public class PaiXu {
/**
* @param args
*/
/**
* 冒泡降序
*
* @param a
* @return
*/
public static int[] maoPao(int a[]) {
int c = 0;
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] < a[j + 1]) {
c = a[j];
a[j] = a[j + 1];
a[j + 1] = c;
}
}
}
return a;
}
/**
* 冒泡升序
* @param a
* @return
*/
public static int[] maoPaoShenXu(int a[]){
int c = 0;
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] >a[j + 1]) {
c = a[j];
a[j] = a[j + 1];
a[j + 1] = c;
}
}
}
return a;
}
/**
* 选择降序
*/
public static int[] xuanZe(int a[]) {
for (int i = 0; i < a.length - 1; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[min] < a[j]) {
min = j;
}
}
if (min != i) {
int tem = a[min];
a[min] = a[i];
a[i] = tem;
}
}
return a;
}
/**
* 插入排序 降序
*
* @param a
* @return
*/
public static int[] chaRu(int a[]) {
for (int i = 1; i < a.length; i++) {
if (a[i] > a[i - 1]) {
int tem = a[i];
int j = i;
for (; j > 0; j--) {
if (tem > a[j - 1]) {
a[j] = a[j - 1];
} else {
break;
}
}
a[j] = tem;
}
}
return a;
}
/**
* 显示数组的数目
*
* @param a
*/
public static void show(int a[]) {
for (int b : a) {
System.out.println(b);
}
}
/**
* 二分查找数组 只能查找降序数组
*/
public static void erFenChaZhao(int num, int a[]) {
int head = 0;
int trail = a.length - 1;
int middle = 0;
boolean flag = true;
while (trail >= head) {
middle = (trail + head) / 2;
if (num == a[middle]) {
System.out.println("找到了,位置是第" + (middle + 1) + "个");
flag = false;
break;
} else if (num < a[middle]) {
head = middle + 1;
} else {
trail = middle - 1;
}
}
if (flag) {
System.out.println("没有这个数");
}
}
/**
* 顺序查找
*/
public static void shunXuChaoZhao(int num, int a[]) {
for (int i = 0; i < a.length; i++) {
if (num == a[i]) {
System.out.println("找到了,它是当前数组的第" + (i + 1) + "个");
}
}
}
}
//以前写的一个工具类