码迷,mamicode.com
首页 > 编程语言 > 详细

面试常考各类排序算法总结.(c#)

时间:2017-06-30 12:32:12      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:开始   color   public   ble   bsp   遍历   大于   demo   ons   

一. 面试以及考试过程中必会出现一道排序算法面试题,为了加深对排序算法的理解,在此我对各种排序算法做个总结归纳。

1.冒泡排序算法(BubbleSort)

 1 public Class SortDemo
 2 {
 3      public void BubbleSort(int arr)
 4      {
 5             int temp=0;
 6           //需要走arr.Length-1 趟
 7            for(int i=0;i<arr.Length-1;i++)
 8            {
 9                  //每一趟需要比较次数
10                  for(int j=0,j<arr.Length-i-1;j++)
11                  {
12                      //升序排序
13                       if(arr[j]>arr[j+1])
14                       {
15                                temp=arr[j];//将较大的变量保存在临时变量
16                                arr[j]=arr[j+1];
17                                arr[j+1]=temp;
18                        }   
19                  }
20             }
21          
22      }
23 }

2.直接插入排序(InsertionSort)

public Class SortDemo
{
      public void InsertionSort(int[] arr)
      {
             int temp=0;
             //遍历待插入的数(从第二位开始)
             for(int i=1;i<arr.Length;i++)
             {
                     int j=i-1;//(j为已排序的待插入的位置序号)
                     //若已排序的数大于待插入数,则往后移一位
                     while(j>=0&&arr[j]>arr[i])
                     {
                            arr[j+1]=arr[j];
                            j--;
                      }
                     arr[j+1]=arr[i];//将待插入的数放入插入位置
              }
      }
}

3.选择排序(SelectionSort)

public void SelectionSort(int[] arr)
     {
int temp;
for(int i=0;i<arr.Length-1;i++)
{
int minVal=arr[i];
int minIndex=i;
for(int j=i+1;j<arr.Length;j++)
{
if(minVal>arr[j])
{
minVal=arr[j];
minIndex=j;
}
}
temp=arr[i];
arr[i]=minVal;
arr[minIndex]=temp;
} } }

 

面试常考各类排序算法总结.(c#)

标签:开始   color   public   ble   bsp   遍历   大于   demo   ons   

原文地址:http://www.cnblogs.com/geduocoding/p/7097870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!