面试必备100道经典Java基础题.doc
文本预览下载声明
HYPERLINK /wjbcy/article/details/7485020 面试必备100道经典Java基础题
1.完成数组int[] a = {100,40, 60, 87, 34, 11, 56, 0}的快速排序、冒泡排序;
快速排序
实现代码:
public class Test001 {
??? public static void main(String[] args) {
?????? int[] a = new int[]{100,40, 60, 87, 34, 11, 56, 0};
?????? System.out.println(未排序之前的数据是:);
?????? print(a);
?????? System.out.println(排序之后的数据是:);
?????? sort(a,0,a.length-1);
?????? print(a);
??????
??? }
??? //打印方法
??? public static void print(int[] b){
?????? for(int i=0; ib.length; i++){
?????????? System.out.print(b[i]+ );
?????? }
?????? System.out.println();
??? }
??? //排序方法
??? static void sort(int[] a,int low,int high){
?????? if(low = high) return;//low小于high,则直接返回
?????? if((high - low)==1){//如果只有两个数字,则直接比较
?????????? if(a[0] a[1])
????????????? swap(a,0,1);
?????????? return;
?????? }
?????? int pivot = a[low];//取第一个数作为中间数
?????? int left = low +1;
?????? int right = high;
?????? while(leftright){
?????????? //从左边开始找
?????????? while(left right left = high){//如果左小于右则一直循环
????????????? if(a[left] pivot) break;
????????????? left++;//左下标往右边走一点
?????????? }
?????????? //从右边开始找
?????????? while(left = right right low){//如果左大于右则一直循环
????????????? if(a[right] = pivot)
????????????????? break;
????????????? right--;//右下标往左走一点
?????????? }
?????????? if(left right)//如果还没有找完,则交换数字
????????????? swap(a,right,left);
?????? }
?????? swap(a,low,right);
?????? sort(a,low,right);
?????? sort(a,right+1,high);
??? }
??? //调位方法
??? private static void swap(int[] array, int i, int j){
?????? int temp;
?????? temp = array[i];
?????? array[i] = array[j];
?????? array[j] = temp;
??? }
}打印结果为:
未排序之前的数据是:
100 40 60 87 34 11 56 0
排序之后的数据是:
0 11 34 40 56 60 87 100 ?
冒泡排序
实现代码:
public class Test002 {
??? public static void main(String[] args) {
?????? int[] arr = {100,40, 60, 87, 34, 11, 56, 0};//定义数组
?????? System.out.println(未排序之前的数据是:);
?????? maopaoPrint(arr);
?????? System.out.println();
?????? System.out.println(排序之后的数据是:);
?????? maopaoSort(arr);
??? }
??
显示全部