冒泡排序及二分查找

1.冒泡排序

冒泡排序思路:  两两比较相邻记录的关键字,如果反序则交换,直到没有反序记录为止

代码君:

package com.jacob.DataStructure;
/*
 * 冒泡排序思路:
 *    两两比较相邻记录的关键字,如果反序则交换,直到没有反序记录为止
 */
public class BubbleSortTest {
// 原始方法:
public static void bubbleSort(int[] array) {
// 原始方法:+改进方法:
boolean flag = true;// 添加一个flag判断数组是否进行了交换
for (int i = 0; i < array.length - 1 && flag; i++) {
for (int j = array.length - 2; j >= i; j--) {
flag = false;
if (array[j] > array[j + 1]) {
flag = true;// 若进行了就赋值为true
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}


System.out.println("第" + (i + 1) + "趟排序:");


for (int k = 0; k < array.length; k++) {
System.out.print(array[k] + " ");
}


System.out.println();


}
}


public static void main(String[] args) {
int[] array = { 4, 7, 8, 9, 3, 2 };


bubbleSort(array);


}
}

2.二分查找

二分查找前提:  有序的线性表(关键码有序)

代码君:

package com.jacob.DataStructure;


/*
 * 二分查找:
 * 使用前提是 有序的线性表(有序的关键码):算法性能=logn
 */
public class BinarySearch {
// 普通查找,即顺序查找
public static int search(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (value == array[i]) {
return i;
}
}
return -1;
}


// 二分查找:正是没有对比就没有伤害2333
public static int binarySearch(int[] array, int value) {
int low = 0;
int mid;
int high = array.length - 1;
while (low <= high) {
mid = (high + low) / 2;
if (array[mid] < value) {
low = mid;
} else if (array[mid] > value) {
high = mid;
} else {
return mid;
}
}
return -1;
}


public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int value = 6;
int index = search(a, value);
System.out.println(index);


System.out.println("-----------------");
int[] b = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int index2 = binarySearch(b, value);
System.out.println(index2);
}
}



原文地址:https://www.cnblogs.com/xieji233/p/6155645.html