标签:void red out 排序算法 sele 排序 == font number
本文为排序算法-选择排序的代码实现。
作者水平比较差,有错误的地方请见谅。
简单选择排序:每次选择一个最小的值放到前面。
SelectSort.cs
public static class SelectSort
{
public static void Select(int[] numbers)
{
if (numbers == null || numbers.Length < 2)
{
Console.WriteLine("参数数组有误");
return;
}
//寻找length-1次最小值
for (int i = 0; i < numbers.Length-1; i++)
{
int minIndex = i;
int minNum = numbers[i];
//每次找到最小值放到i的位置
for (int j = i; j < numbers.Length; j++)
{
if (numbers[j] < minNum)
{
minIndex = j;
minNum = numbers[j];
}
}
//i位置值和每次找到的最小值交换
if (minIndex != i)
{
int temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
int[] numbers = { 49, 38, 65, 97, 76, 13, 27, 49 };
SelectSort.Select(numbers);
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(numbers[i] + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
SelectSort.cpp
///选择排序
class SelectSort
{
public:
static void Select(int numbers[],int length);
};
void SelectSort::Select(int numbers[],int length)
{
if (numbers == NULL || length < 2)
{
cout<<"参数数组有误"<<endl;
return;
}
for (int i = 0; i < length-1; i++)
{
int minIndex = i;
int minNum = numbers[i];
for (int j = i; j < length; j++)
{
if (numbers[j] < minNum)
{
minIndex = j;
minNum = numbers[j];
}
}
if (minIndex != i)
{
int temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}
}
main.cpp
int numbers[] = {49,38,65,97,76,13,27,49};
int length = sizeof(numbers)/sizeof(numbers[0]);
SelectSort::Select(numbers,length);
for(int i=0;i<length;i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
numbers = {49,38,65,97,76,13,27,49}
length = #numbers
function SelectSort(nums)
local length = #nums
if (nums == nil or length < 2) then
print("参数数组有误")
return
end
for i=1,length-1,1 do
local minIndex = i
local minNum = numbers[i]
for j=i,length,1 do
if (numbers[j] < minNum) then
minIndex = j
minNum = numbers[j]
end
end
if (minIndex ~= i) then
local temp = numbers[i]
numbers[i] = numbers[minIndex]
numbers[minIndex] = temp
end
end
end
SelectSort(numbers)
for i=1,length,1 do
io.write(numbers[i] .. ' ')
end
print()
标签:void red out 排序算法 sele 排序 == font number
原文地址:https://www.cnblogs.com/Fflyqaq/p/11823641.html