就地归并排序| c#
本文关键字:归并排序 | 更新日期: 2023-09-27 18:10:01
我已经写了一个程序,用于合并排序和程序工作良好,直到在合并点,它不能正确合并
例如:
mergesort.in://所有数字都是一个数组,不使用临时数组进行排序
- 2//-->This is Array Number
- 5//-->This is Array(next line) Length
- 4 6 98 8 24
- 8//-->This is Array(next line) Length
- 12 14 89 21 4 7 9 41
归并排序。:
//Output in file mergesort.Out
- 4 6 8 24 98
- 4 7 9 12 14 21 41 89
我不明白如何为就地合并排序工作mergeArray函数
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class ReadFromFile
{
static void Main()
{
ArrayList lines = new ArrayList();
var input = System.IO.File.ReadAllLines(@"C:'mergesort.in");
System.Console.WriteLine("Contents of mergesort.in = ");
foreach (string line in input)
{
Console.WriteLine("'t" + line);
}
foreach (var i in input)
{
if (Convert.ToInt32(i.Length) > 1)
{
var counter = 0;
foreach (var item in input)
{
if (input[counter].Length > 1)
{
string[] t = input[counter].Split(' ');
foreach (string word in t)
{
lines.Add(word);
}
ReadFromFile.mergesort(t, 0, 5, lines);
}
counter++;
}
foreach (string line in lines)
{
Console.WriteLine("'t" + line);
}
break;
}
}
Console.WriteLine("Press any key to exit...");
System.Console.ReadKey();
}
private static void mergesort(string[] t, int p1, int p2, ArrayList lines)
{
if (p1 < p2)
{
int mid = (p2 + p1) / 2;
ReadFromFile.mergesort(t, p1, mid, lines);
Console.WriteLine(p1);
ReadFromFile.mergesort(t, mid + 1, p2, lines);
Console.WriteLine(t);
foreach (var item in t)
{
Console.WriteLine(item);
}
ReadFromFile.mergeArray(t, p1, mid, p2, lines);
}
}
private static void mergeArray(string[] arr, int start, int mid, int end, ArrayList lines)
{
//I'm not understand how to work this function for in-place merge Sort
}
}
}
如果使用Linq:
就容易多了foreach (var line in input)
{
var elements = line.Split(' ');
if (elements.Count > 1)
{
var t = elements
.Select(i => Convert.ToInt32(i))
.Distinct()
.OrderBy(i => i)
.Select(i => i.ToString())
.ToArray();
Console.WriteLine("'t" + string.Join(" ", t));
}
}
如果要合并多个数组中的唯一值,则使用.Union