二分查找和快速排序分别是查找和排序算法中最重要的算法。下面代码采用java语言来进行编写。
public class BinarySearch {
/**
* 折半查找
* @param 所要查找的数组, 要查找的关键字
* @return 如果找到,则返回元素在数组中的下标,否则返回-1
*/
public static int binarySearch(int[] nums, int key){
int low = 0;
int high = nums.length - 1;
while(low <= high){
int mid = (low + high) / 2;
if(nums[mid] == key){
return mid;
}else if(nums[mid] > key){
high = mid - 1;
}else{
low = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums = {1,2,3,4,5,6,7,8,9};
int result = binarySearch(nums, 11);
if(result == -1){
System.out.println("数组中没有该关键字");
}else{
System.out.println("该关键字在数组中的下标为:" + result);
}
}
}
public class QuickSort {
public static void quickSort(int[] nums, int low, int high){
if(low < high){
int i = low;
int j = high;
int pivot = nums[i];
while(i <j){
while(i <j && nums[j] >= pivot){
j--;
}
if(i <j){
nums[i] = nums[j];
i++;
}
while(i <j && nums[i] <= pivot){
i++;
}
if(i <j){
nums[j] = nums[i];
j--;
}
}
nums[i] = pivot;
quickSort(nums, low, i -1);
quickSort(nums, i + 1, high);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums = {49,38,65,97,76,13,27,49};
quickSort(nums, 0, 7);
for(int i = 0; i<nums.length; i++){
System.out.print(nums[i]+" ");
}
}
}