C#算法----(二)插入排序

 


朋友们,我最近加紧写C#的一些算法。选择排序已经推出的。现推出插入算法。
对想提高C#语言编程能力的朋友,我们可以互相探讨一下。
如:下面的程序,并没有实现多态,来,帮它实现一下。
using System;
public class InsertionSorter
{
  public void Sort(int [] list)
  {
      for(int i=1;i<list.Length;++i)
      {
          int t=list[i];
          int j=i;
          while((j>0)&&(list[j-1]>t))
          {
            list[j]=list[j-1];
            --j;
          }
        list[j]=t;
      }

    }
}
public class MainClass
{
    public static void Main()
    {
    int[] iArrary=new int[]{1,5,3,6,10,55,9,2,87,12,34,75,33,47};
    InsertionSorter ii=new InsertionSorter();
    ii.Sort(iArrary);
    for(int m=0;m<=13;m++)
    Console.WriteLine("{0}",iArrary[m]); 
      }
}
已经编译运行通过.这太简单了,我不做详细介绍了.

阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C# 中常用的排序算法有以下几种: 1. 冒泡排序 冒泡排序是一种简单的排序算法,每次比较相邻两个元素的大小并交换位置,重复进行直到数组有序。具体实现如下: ```csharp public static void BubbleSort(int[] arr) { int n = arr.Length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } ``` 2. 插入排序 插入排序是一种简单且有效的排序算法,将未排序的元素依次插入到已排序的序列中,直到所有元素都有序。具体实现如下: ```csharp public static void InsertionSort(int[] arr) { int n = arr.Length; for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } ``` 3. 选择排序 选择排序是一种简单的排序算法,每次选择数组中最小的元素并将其放到已排序的序列的末尾,直到所有元素都有序。具体实现如下: ```csharp public static void SelectionSort(int[] arr) { int n = arr.Length; for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } } ``` 4. 快速排序 快速排序是一种高效的排序算法,它使用分治的思想将数组分成两个子数组,然后递归地对这两个子数组进行排序,最后合并两个有序数组。具体实现如下: ```csharp public static void QuickSort(int[] arr, int left, int right) { if (left < right) { int pivotIndex = Partition(arr, left, right); QuickSort(arr, left, pivotIndex - 1); QuickSort(arr, pivotIndex + 1, right); } } private static int Partition(int[] arr, int left, int right) { int pivot = arr[right]; int i = left - 1; for (int j = left; j < right; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp1 = arr[i + 1]; arr[i + 1] = arr[right]; arr[right] = temp1; return i + 1; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

solarsoft

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值