Java基本的六种排序(方法部分)

本文介绍了六种经典的排序算法,包括插入排序、选择排序、冒泡排序、计数排序、归并排序和堆排序,并提供了每种算法的Java实现代码。通过这些代码示例,读者可以更好地理解各种排序算法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.简单插入排序

public class Insertion {

 /**
  * @param args
  */
 public static void insertion_Sort(int a[])
 {
  int temp = 0;
  for(int i=1;i<a.length;i++)
  {
   temp = a[i];
   int j = i-1;
   while(j>=0 && a[j]>temp)
   {
    a[j+1] = a[j];
    j--;
   }
   a[++j] = temp;
  }
 }

2.选择排序

/*
这种方法,我觉得又可以叫做错位排序
外层循环和内层循环的长度都是length-1,外层从i到length-2;内层从i+1到length-1。
时间复杂度:O(n2)
*/

public class Selection {

 /**
  * @param args
  */
 public static void selection_Sort(int a[])
 {
  int temp = 0;
  for(int i=0;i<a.length-1;i++)
   for(int j=i+1;j<a.length;j++)
    if(a[i]>a[j])
    {
     temp = a[i];
     a[i] = a[j];
     a[j] = temp;
    }
 }

3.冒泡排序(改进)

public static void bubble_Sort(int a[])
 {
  int temp = 0;
  int count=0;
  for(int i=0;i<a.length;i++)
  {
   boolean change=true;
  
   for(int j=0;j<a.length-i-1;j++)
   {
    if(a[j]>a[j+1])
    {
     temp = a[j];
     a[j] = a[j+1];
     a[j+1] = temp;
     change=false;
    }
   }
   if(change)
   {
    break;
   }
   count++;
  }
 }

4.计数排序

 public static void count_Sort(int a[])
 {
  int count;
  int b[] = new int[a.length];
  for(int i=0;i<a.length;i++)
  {
   count = 0;
   for(int j=0;j<a.length;j++)
   {
    if(a[i]>a[j])
     count++;
    if(a[i]==a[j] && i>j)
     count++; 
   }
   b[count] = a[i];
  }
  for(int n=0;n<a.length;n++)
   a[n] = b[n];
 }

5.归并排序

 public static void merge_Sort(int a[])
 {
  int temp[] = new int[a.length];
  merge_Sort(a,temp,0,a.length-1);
 }
 private static void merge_Sort(int a[],int temp[],int l,int r)
 {
  int mid = (l+r)/2;
  if(l==r) return;
  merge_Sort(a,temp,l,mid);
  merge_Sort(a,temp,mid+1,r);
  for(int i=l;i<=r;i++)
   temp[i] = a[i];
  int i1 = l;
  int i2 = mid+1;
  for(int j=l;j<=r;j++)
  {
   if(i1==mid+1)
    a[j] = temp[i2++];
   else if(i2>r)
    a[j] = temp[i1++];
   else if(temp[i1]<temp[i2])
    a[j] = temp[i1++];
   else
    a[j] = temp[i2++];
  }
 }

6.堆排序

public class HeapSort
{
 void adjust(int a[],int length,int m)
 {
  int k;
  int i = m;
  int j = 2*m;
  while(j<length)
  {
   k = max(a,length,j,j+1);
   if(a[i]<a[k])
   {
    int temp = a[i];
    a[i] = a[k];
    a[k] = temp;
    i = k;
    j = 2*i;
   }
   else break;
  }
 }
 private int max(int a[],int length,int i,int j)
 {
  if(j==length) return i;
  return a[i]>a[j] ? i : j;
 }
 public void heap_Sort(int a[])
 {
  for(int i=a.length/2;i>=1;i--)
   this.adjust(a,a.length,i);
  for(int i=a.length-1;i>=1;i--)
  {
   int temp = a[1];
   a[1] = a[i];
   a[i] = temp;
   this.adjust(a,i,1);
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值