一、冒泡排序

数组排序与查找 - 图1
像冒泡泡一样,大的往上冒泡泡。。。
相邻的元素比较大小,如果前一个元素比后一个元素大,则交换位置

  1. int[] score = {1, 2, 3, 4, 5,1,3,32,4,3,4,3,43,432};
  2. System.out.println("通过冒泡排序方法对数组进行排序:");
  3. for(int i=0;i<score.length-1;i++){
  4. for(int j=i+1;j<score.length;j++){
  5. if(score[j] > score[i] ){//如果后面的大于前面的,做一个交换
  6. int temp = score[j];
  7. score[j] = score[i];
  8. score[i] = temp;
  9. }
  10. }
  11. }
  12. for (int i : score) {
  13. System.out.println(" " +i );
  14. }

二、二分查找

  1. int[] score = {1,2,3,4,5,6,8,9,10,11};
  2. int value = 12;
  3. int index = -1;
  4. int start = 0;
  5. int end = score.length-1;
  6. while(start <= end){
  7. int mid = (start + end) >>> 1;
  8. if(value == score[mid]){
  9. index = mid;
  10. break;
  11. }else if(value < score[mid]){
  12. end = mid-1;
  13. }else if(value > score[mid]){
  14. start = mid+1;
  15. }
  16. }
  17. if(index == -1){
  18. System.out.println("未找到");
  19. }else {
  20. System.out.println("index = " + index);
  21. }