2013-02-18 71 views
-2

我是编程新手,刚刚听说过排序。我经历了排序的基础知识,发现插入排序是最简单的。但事情是,我不明白它是什么!你能详细解释我什么是插入排序以及如何实现它。在C#中的实现将不胜感激。什么是插入排序?

任何帮助将不胜感激! :)

+0

你看维基百科? – 2013-02-18 14:08:10

+0

http://en.wikipedia.org/wiki/Insertion_sort维基百科已经有了详细的解释。任何你不明白的东西?请指出。 – luiges90 2013-02-18 14:08:26

+0

Stackoverflow不是Google。见http://en.wikipedia.org/wiki/Insertion_sort – 2013-02-18 14:08:37

回答

1

乘坐战利品在Wikipedia

插入排序的算法是

int temp, j; 

for (int i=1; i < vector.length; i++){ 
    temp = vector[i]; 
    j = i-1; 

    while (j >= 0 && vector[j] > temp){ 
    vector[j + 1] = vector[j]; 
    j--; 
    } 

    vector[j+1] = temp; 
} 
0

插入排序比我们之前(冒泡排序和选择排序)为已经实现了算法的更有效排序一个小数据集。插入排序主要在列表部分排序时使用。我们假设第一个元素被排序。然后我们检查相邻的索引是否更小或更大。如果值较小,我们将它插入索引[0]的左侧,这意味着现在较小的值位于索引[0]处,并且如果它大于索引[0]的原始值,则我们得到一个排序列表2元素。我们对相邻元素实施相同的方法。然后将它与以前的元素进行比较以创建一个排序列表。所以基本上 - 你将最终在数组左侧进行排序列表,并在一个阶段右侧排序。记住,我们回去检查数组是否已排序 - 除非相关元素(包括相关元素)后面的数组完全排序,否则我们不会前进。

这里的插入的C#实现排序:

class Program 
    { 
     static void Main(string[] args) 
     { 
      int i, j; 
      int[] unsortedarrayed = new int[] { 34, 36, 2, 7, 8, 3, 6, 5 }; 

      for (i = 0; i < unsortedarrayed.Length; i++) 
      { 
       Console.WriteLine(unsortedarrayed[i]); 
      } 

      int[] sortedarray = InsertionSorted(unsortedarrayed); 

      for (i = 0; i < sortedarray.Length; i++)  
      { 
       Console.WriteLine(sortedarray[i]); 
      } 

      Console.Read(); 
     } 

     public static int[] InsertionSorted(int[] unsortedarrayed) 
     { 
      for (int i = 1; i < unsortedarrayed.Length; i++) 
      { 
       int temp = unsortedarrayed[i]; 
       int j = i - 1; 

       while ((j > -1) && (unsortedarrayed[j] > temp)) 
       { 
        int tempo = unsortedarrayed[j + 1]; 
        unsortedarrayed[j + 1] = unsortedarrayed[j]; 
        unsortedarrayed[j] = tempo; 

        j = j - 1; 
       } 
      } 

      return unsortedarrayed; 
     } 
    } 

来源: 对于更详细点击以下链接: 1)Link 1 2)Link 2

+0

好吧,你能至少格式化代码并删除多余的语句吗? – 2013-02-18 14:13:14

+0

代码无法正常工作! – 2013-02-18 14:37:09