冒泡排序,选择排序,插入排序

冒泡排序

public static void BubbleSort()
{
  var a = new[] { 10, 23, 14, 24, 57, 3, 7, 19, 87, 11 };
  int i, j, temp;
  for (i = a.Length - 1; i > 1; i--)
  {
      for (j = 0; j < i; j++)
      {
          if (a[j] > a[j + 1])
          {
              temp = a[j];
              a[j] = a[j + 1];
              a[j + 1] = temp;
          }
      }
  }         
}

选择排序

public static void SelectionSort()
{
	var a = new[] { 10, 23, 14, 24, 57, 3, 7, 19, 87, 11 };
	int i, j, temp, min;
	for (i = 0; i < a.Length - 1; i++)
	{
		min = i;
		for (j = i+1; j < a.Length; j++)
		{
			if (a[j] < a[min])
			{
				min = j;
			}
		}
		temp = a[i];
		a[i] = a[min];
		a[min] = temp;
	}	
}
//自己写的,固定最新在第一个数,能减少交换次数
public static void SelectionSort2()
{
	var a = new[] { 10, 23, 14, 24, 57, 3, 7, 19, 87, 11 };
	int i, j, temp;
	for (i = 0; i < a.Length - 1; i++)
	{
		temp = a[i];
		for (j = i + 1; j < a.Length; j++)
		{
			if (a[j] < a[i])
			{
				a[i] = a[j];
				a[j] = temp;
			}
		}                       
	}
}

插入排序

public static void InsertionSort()
{
	var a = new[] { 10, 23, 14, 24, 57, 3, 7, 19, 87, 11 };
	int i, j, temp;
     for (i = 1; i < a.Length; i++)
    {
         temp = a[i];
         j = i;
         while (j> 0 && (a[j-1]>=temp))
         {
             a[j] = a[j - 1];
             --j;
         }
         a[j] = temp;
     }	
	foreach (var i1 in a)
	{
		Console.WriteLine(i1);
	}
	Console.Read();
}

你可能感兴趣的:(算法)