java基础知识之 算法 【冒泡排序】【快速排序】

来源:互联网 发布:vscode前端插件 编辑:程序博客网 时间:2024/06/08 04:37

 

/**

@auther:kevin

@function:

 冒泡排序(BubbleSort)的基本概念是:依次比较相邻的两个数,将小数放在前面,大数放在后面。即在第一趟:首先比较第1个和第2个数,将小数放前,大数放后。然后比较第2个数和第3个数,将小数放前,大数放后,如此继续,直至比较最后两个数,将小数放前,大数放后。至此第一趟结束,将最大的数放到了最后。在第二趟:仍从第一对数开始比较(因为可能由于第2个数和第3个数的交换,使得第1个数不再小于第2个数),将小数放前,大数放后,一直比较到倒数第二个数(倒数第一的位置上已经是最大的),第二趟结束,在倒数第二的位置上得到一个新的最大数(其实在整个数列中是第二大的数)。如此下去,重复以上过程,直至最终完成排序。
  由于在排序过程中总是小数往前放,大数往后放,相当于气泡往上升,所以称作冒泡排序。
*/


public class BubbleSort
{
 public static void main(String args[]){
 int a[] = {110,23,1,12,34,23} ; //定义一个数组
 int temp;  //temp用于存储
 for(int i=1;i <=a.length-1;i++)
 {
  for (int j=0;j<=a.length-1-i; j++)
  {
   if(a[j]>a[j+1])//如果前一个数大于后一个数
   {
    temp = a[j+1];  //a[j]与a[j+1]调换位置
    a[j+1] = a[j];
    a[j] = temp;
   }
  }
 }
 for(int i=0;i <a.length;i++)
 System.out.println(a[i]);
 }
}

 

 

 

-------------------------------------------------------------------------

 【快读排序】

import java.util.Arrays;

/**
 * 快速排序
 * @author Administrator
 *
 */
public class QuickSort {
/**
 * 一趟比较划分结果
 * @param sortIn 传入的数组
 * @param i 区间下界
 * @param j 区间上界
 * @return 返回基准最终位置
 */
  private static int partition(Integer[] sortIn, int i, int j) {
  
         int pivot = sortIn[i];  
         while (i < j) {  
             // 从右向左扫描,查找第一个关键字小于pivot的记录  
             while (i < j && sortIn[j] >= pivot)  
                 j--;  
             if (i < j) {  
                 swap(sortIn, i, j);// 交换sortIn[i]和sortIn[j]  
                 i++;  
             }  
  
            // System.out.println("从右向左扫描:" + Arrays.asList(sortIn).toString());  
               
             // 从左向右扫描,查找第一个关键字大于pivot的记录  
             while (i < j && sortIn[i] <= pivot)  
                 i++;  
             if (i < j) {  
                 swap(sortIn, i, j);  
                 j--;  
             }  
               
            // System.out.println("从左向右扫描:" + Arrays.asList(sortIn).toString());  
         }  
         sortIn[i] = pivot;// 基准位置已被最终定位  
         //System.out.println("标记:" + pivot);  
         return i;  
     } 
  /**
   * 递归实现快速排序
   * @param sortIn
   * @param low
   * @param high
   */
    public static void quickSort(Integer[] sortIn, int low, int high) {  
         int pivotpos;// 划分后的基准记录的位置  
         if (low < high) {// 仅当区间长度大于1时才需排序  
             pivotpos = partition(sortIn, low, high);// 做划分  
             quickSort(sortIn, low, pivotpos - 1);// 对左区间进行递归排序  
             quickSort(sortIn, pivotpos + 1, high);// 对右区间进行递归排序  
         }
        
     }  

 
  private static void swap(Integer[] sortIn, int i, int j) {
   // TODO Auto-generated method stub
   int temp = sortIn[i];
   sortIn[i] = sortIn[j];
   sortIn[j] = temp;
   
  }
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Integer[] a=new Integer[] { 8, 6, 1, 5, 4 };
  quickSort(a,0,a.length-1);
  System.out.println("最终结果:" + Arrays.asList(a).toString());  
 }

}

 

原创粉丝点击