Saturday, 15 September 2012

algorithm - in-place Merge Sort | C# -



algorithm - in-place Merge Sort | C# -

this question has reply here:

how sort in-place using merge sort algorithm? 10 answers

i have written programme merge sort , programme works fine until @ point of merging doesn't merge

such example:

mergesort.in: // number 1 array , not utilize temp array sorting

2 //-->this array number 5 //-->this array(next line) length 4 6 98 8 24 8 //-->this array(next line) length 12 14 89 21 4 7 9 41

mergesort.out:

//output in file mergesort.out 4 6 8 24 98 4 7 9 12 14 21 41 89

i'm not understand how work mergearray function in-place merge sort

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 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 key 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 work function in-place merge sort } } }

it much easier if utilize 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)); } }

use .union if want merge unique values more 1 array

c# algorithm search mergesort in-place

No comments:

Post a Comment