Hi ,
i need code , which is used for sorting in c# i.e. .sort method code., somewhere i read that they use quick sort algorithm , can anyone plz help me by giving the code.
Thanks in Advance
Hi ,
i need code , which is used for sorting in c# i.e. .sort method code., somewhere i read that they use quick sort algorithm , can anyone plz help me by giving the code.
Thanks in Advance
A clear, practical plan for sorting a text file (lines) and some pitfalls to avoid.
Many replies already showed the basic options: the quickest solution is to read the file, sort the lines, and write the result. gave that simple approach and posted a hand-rolled quicksort (useful to learn from). For real programs, prefer a small, safe workflow: read/normalize, choose the right comparer, write to a temporary file, then atomically replace the original. That avoids corrupting the input if something fails.
A compact, safe in-memory pattern (good when the file fits comfortably in RAM):
using (var r = new StreamReader(inPath, Encoding.UTF8))
using (var w = new StreamWriter(tempPath, false, Encoding.UTF8))
{
string header = r.ReadLine(); // optional: preserve header
if (header != null) w.WriteLine(header);
var lines = new List<string>();
string s;
while ((s = r.ReadLine()) != null)
{
s = s.Trim();
if (s.Length == 0) continue; // optional: skip blanks
lines.Add(s);
}
lines.Sort(StringComparer.OrdinalIgnoreCase); // choose comparer carefully
foreach (var line in lines) w.WriteLine(line);
}
File.Replace(tempPath, inPath, backupPath: null); // atomic swap If the file is too large for memory, do an external (chunked) sort: read fixed-size chunks, sort each chunk to a temp file, then perform a k‑way merge of those sorted chunk files (use a min‑heap / PriorityQueue to pick the next line from the chunk files). Pseudocode:
while not EOF: read N lines -> sort -> write chunk_i
open all chunk readers; push first line from each into heap
while heap not empty: pop smallest -> write -> refill from that reader Practical tips: pick StringComparer based on culture or use numeric parsing for numeric keys; be explicit about encoding; preserve headers if present; test on copies before replacing originals; and use chunked merge for files bigger than available memory. This covers the safe, production-ready approaches that build on the earlier examples in the thread.
Jump to Post— ddanbe 2,724The sort method code may be different depending on the class were it belongs to.
I don't know and I really don't care very much, as long as it does the job!
Also have a look at this excellent snippet : http://www.daniweb.com/software-development/csharp/code/351309
Jump to Post— Mitja Bonca 557Hello
would you mind telling to Sort what exactly?
An array, listArray, generic list<T>, dictionary collections, or else?You have to be specific, and which technique do you want to use?
For the Arrays there is a method "Sort" avaiable, then you have a Linq, a very powerful …
The sort method code may be different depending on the class were it belongs to.
I don't know and I really don't care very much, as long as it does the job!
Also have a look at this excellent snippet : http://www.daniweb.com/software-development/csharp/code/351309
Hello
would you mind telling to Sort what exactly?
An array, listArray, generic list<T>, dictionary collections, or else?
You have to be specific, and which technique do you want to use?
For the Arrays there is a method "Sort" avaiable, then you have a Linq, a very powerful tool in C# (since version 2.0 and leter). Using Lambda Expressions, allows you to do almost any kind of sorting and stuff.
In linq you use methods like "Sort, and OrderBy, but a bit differently then for the Array.
//1. array Sort:
string[] strArray = { "b", "d", "a" };
int[] intArray = { 23, 43, 3, 2 };
Array.Sort(strArray); //asc
Array.Reverse(strArray); //des
Array.Sort(intArray);//asc
//2.Linq on generic List<T>:
List<string> list1 = new List<string>();
list1.AddRange(new string[] { "b", "d", "a" });
list1 = list1.OrderBy(o => o[0]).ToList();
List<int> list2 = new List<int>();
list2.AddRange(new int[] { 23, 43, 3, 2 });
list2.Sort((x, y) => Convert.ToInt32(x).CompareTo(Convert.ToInt32(y)));
//to show results:
foreach (int number in list2)
{
//number is the value (one by one - in sorted ascending order!
} This is the most quick sorting algorithm I know:
namespace sort
{
class Program
{
static void Main(string[] args)
{
List<string> sortList = new List<string>();
sortList.Add("X");
sortList.Add("B");
sortList.Add("K");
sortList.Sort();
for(int i = 0; i < sortList.Count; i++ ) Console.WriteLine(sortList[i]);
Console.ReadKey();
}
}
} But it may not work in your case..... e.g. when you have to sort objects. In that case the class you want to sort should implement the interface IComparer. See http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx
hi ,
i appreciate you , but as i am new in .Net i am not getting what i have to do.
i want to read text(.txt) file and want to sort it accordingly , the link that you have given to me from that i am not getting from where to read my text file and how to sort it,
can you plz help me for this.
Thanks in Advance
:)
Do you want to sort the text line in the text-file?
In that case you have to read all lines from the text-file and add them to List<string> sortList = new List<string>(); After that you can sort the List and write it to another/the text-file
Do you want to sort the text line in the text-file?
In that case you have to read all lines from the text-file and add them to List<string> sortList = new List<string>(); After that you can sort the List and write it to another/the text-file
It's much easier than that:
string[] lines = File.ReadAllLines("MyFile.txt");
Array.Sort(lines);
File.WriteAllLines("MyFile.txt", lines); using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace quik
{
class Quicksort
{
public static void qsort(string[] items)
{
qs(items, 0, items.Length - 1);
}
static void qs(string[] items, int left, int right)
{
int i, j;
string x, y;
i = left; j = right;
x = items[(left + right) / 2];
do
{
while ((items[i].CompareTo(x)< 0) &&(i < right)) i++;
while ((x.CompareTo(items[j])<0) && (j > left)) j--;
if (i <= j)
{
y = items[i];
items[i] = items[j];
items[j] = y;
i++; j--;
}
} while (i <= j);
if (left < j) qs(items, left, j);
if (i < right) qs(items, i, right);
}
}
public class QS
{
public static void Main()
{
// char[] a = { 'v', 'i', 'r', 'e', 'n', 'd', 'r' ,'a'};
string[] a = System.IO.File.ReadAllLines(@"C:\\3.txt");
int i;
//Console.Write("Original array: ");
//for (i = 0; i < a.Length; i++)
// Console.Write(a[i]);
//Console.WriteLine();
Quicksort.qsort(a);
using (System.IO.StreamWriter abc = new System.IO.StreamWriter(@"C:\write11.txt"))
{
for ( i = 0; i < a.Length; i++)
{
abc.WriteLine("{0}", a[i]);
}
}
//for (i = 0; i < a.Length; i++)
// Console.Write(a[i]);
}
}
} We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.