C#ソートアルゴリズムレコード
9682 ワード
class Program
{
static void Main(string[] args)
{
var array = new[] { 11, 3, 24, 5, 0, 2, 4, 6, -1, 101, 101, 5 };
//
var minnum = array[0];
for (int i = 0; i < array.Length; i++)
{
if (array[i] < minnum)
{
minnum = array[i];
}
}
//
var maxnum = array[0];
for (int i = 0; i < array.Length; i++)
{
if (array[i] > maxnum)
{
maxnum = array[i];
}
}
Console.WriteLine("Min:" + minnum);
Console.WriteLine("Max:" + maxnum);
Console.WriteLine("======= ========");
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length - i - 1; j++)
{
var temp = 0;
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
//
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]+" ");
}
Console.WriteLine("\r
======= ========");
//
var list = new List<int> { 11, 3, 24, 5, 0, 2, 4, 6, -1, 101, 101, 5 };
QuickSort(list, 0, list.Count );
foreach (var item in list)
{
Console.Write(item+" ");
}
//
Console.ReadLine();
}
/// <summary>
///
/// </summary>
/// <param name="nums"> </param>
/// <param name="left"> </param>
/// <param name="right"> </param>
private static void QuickSort(List<int> nums, int left, int right)
{
if (left < right)
{
int i = left;
int j = right - 1;
int middle = nums[(left + right) / 2];
while (true)
{
while (i < right && nums[i] < middle)
{
i++;
}
while (j > 0 && nums[j] > middle)
{
j--;
}
if (i == j) break;
nums[i] = nums[i] + nums[j];
nums[j] = nums[i] - nums[j];
nums[i] = nums[i] - nums[j];
if (nums[i] == nums[j]) j--;
}
QuickSort(nums, left, i);
QuickSort(nums, i + 1, right);
}
}
}