现在的位置: 首页 > 综合 > 正文

C#实现的3种排序算法–冒泡排序、选择排序、插入排序

2017年10月21日 ⁄ 综合 ⁄ 共 1575字 ⁄ 字号 评论关闭
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
  
class Program
  {
    
static void Main(string[] args)
    {
      
int[] iarrary = new int[] {1,5,13,6,10,55,99,2,87,12,34,75,33,47};
         
//mpsort(iarrary);
         
// xzsort(iarrary);
      crsort(iarrary);
      
for (int n = 0; n < iarrary.Length; n++)
      {
        Console.WriteLine(
"{0}",iarrary[n]);
      }
      Console.Read();
    }

    public static void mpsort(int [] list)//冒泡排序
    {
      
int i, j, temp;
      
bool exchange;
      
for (i = 1; i < list.Length; i++)//最多做list.Length-1趟排序
      {
        exchange 
= false;
        
for (j = 0; j < list.Length-i;j++ )
        {
          
if(list[j]>list[j+1])
          {
            temp 
= list[j];
            list[j] 
= list[j + 1];
            list[j 
+ 1= temp;
            exchange 
= true;
          }
        }
        
if (!exchange)
        {
          
break;
        }
      }
    }

    public static void xzsort(int[] list)//选择排序
    {
      
int i,j,temp,min;
      
for (i = 0; i < list.Length; i++)
      {
        min 
= i;
        
for (j = i + 1; j < list.Length;j++ )
        {
          
if (list[min] > list[j])
          {
            min 
= j;
          }
        }
        temp 
= list[min];
        list[min] 
= list[i];
        list[i] 
= temp;
      }
    }

    public static void crsort(int[] list)//插入排序
    {
      
int i,j,temp;
      
for (i = 1; i < list.Length; i++)
      {
        temp 
= list[i];
        j 
= i;
        
while((j > 0)&&(list[j-1]>temp))
        {
          list[j]
=list[j-1];
          
--j;
        }
        list[j]
=temp;
      }
    }
  }
}

 

抱歉!评论已关闭.