110,533
社区成员
发帖
与我相关
我的任务
分享
static void SwapZero(List<int> list,int count) {
// 0与数组末尾项交换
for (int i = 0; i < count; i++)
{
if (list[i] == 0)
{
list[i] = list[count - 1];
list[count - 1] = 0;
break;
}
}
// 将最大值与0交换
for (int i = 0; i < count; i++)
{
if (list[i] == count - 1) {
list[count - 1] = list[i];
list[i] = 0;
break;
}
}
if (count > 1)
{
SwapZero(list, count - 1);
}
}
static void Main()
{
List<int> list = new List<int> { 1, 5, 4, 2, 3, 0};
SwapZero(list,list.Count);
list.ForEach(x => { Console.Write(x.ToString() + " "); });
Console.Read();
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int> { 1, 5, 4, 2, 3, 0, 6 };
for (int i = 1; i < list.Count; i++)
{
if (list[i] != i)
swap(list, i);
}
list.ForEach(x => { Console.Write("{0} ", x); });
Console.WriteLine("................Press any key");
Console.ReadKey();
}
private static void swap(List<int> list, int index)
{
var 数0的位置 = (from i in Enumerable.Range(0, list.Count)
where list[i] == 0
select i).First();
var 数index的位置 = (from i in Enumerable.Range(0, list.Count)
where list[i] == index
select i).First();
swap2(list, 数0的位置, index); //此时数0交换到index位置
swap2(list, index, 数index的位置);
}
private static void swap2(List<int> list, int i, int j)
{
if (i != j)
{
var tmp = list[i];
list[i] = list[j];
list[j] = tmp;
}
}
}
}
如果每一次都需要搜索数0所在的新位置(而不是位置0)才能交换,那么就需要先搜索。从方法swap中可以看到两次调用swap2时其中一个位置中都必定有数0存在。
List<int> list = new List<int> { 1, 5, 4, 2, 3, 0 ,6};
for (int i = 0; i < list.Count; i++)
{
int temp;
temp = list[i];
list[i] = list[temp];
list[temp] = temp;
}
list.ForEach(x => { Console.Write(x.ToString() + " "); });