主要排序算法Java实现

发表于:2010-5-14 10:28

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

  3,插入排序

public class InsertSortImpl {
  /**
  * @param args
  */
  public static void InsertSort(int A[]) {
  int n = A.length;
    for (int i = 0; i < n-1; i++) {
      int temp = A[i+1];
      Insert(A, temp, i );
    }
  }
  public static void Insert(int A[], int e, int k) {// 对A[1...k]排序
    while(k>=0&&A[k]>e){
      A[k+1]=A[k];
      k--;
    }
  A[k+1]=e;
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int A[] = new int[] { 2, 5, 3, 9, 7, 1, 30,6 };
    InsertSort(A);
    for (int i = 0; i < A.length; i++) {
    System.out.println(A[i]);
    }
  }
}

  4,快速排序

import java.util.Random;
public class QuickSortImpl {
  /**
  * @param args
  */
  public static void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
  }

  public static void QuickSort(int A[], int left, int right) {
    if (left < right) {
    int i = left;
    int j = right;
    int pivot = A[left];
    while(left<right){

      while(A[left]<pivot) {
      ++left;
      }
      while(A[right]>pivot){
      --right;
      }

      if(left<right){
        int temp=A[left];
        A[left]=A[right];
        A[right]=temp;
      }
      }
    int temp=A[right];
    A[right]=pivot;
    pivot=temp;
    QuickSort(A, i, right- 1);
    QuickSort(A, right+1, j);
    }
  }
  public static void main(String[] args) {
  // TODO Auto-generated method stub
  int A[]=new int[]{3,7,2,35,8,9};
  QuickSort(A,0,5);
    for(int i=0;i<5;i++){
    System.out.println(A[i]);
    }
  }
}

32/3<123>
《2023软件测试行业现状调查报告》独家发布~

精彩评论

  • kettleyang
    2010-5-14 11:18:17

    A[j+1]=temp;//直接调用Swap会出错。why?
    java 值传递

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号