Array Sort
In this chapter you will learn:
- How to sort an array
- Sort an array and search for a value
- Implementing IComparable and sort by Array.Sort
- Array.Sort by CultureInfo
Sort an array
using System; //from j a v a 2 s.co m
class MainClass {
public static void Main() {
int[] nums = { 5, 4, 6, 3, 14, 9, 8, 17, 1, 24, -1, 0 };
Console.Write("Original order: ");
foreach(int i in nums){
Console.Write(i + " ");
}
Console.WriteLine();
Array.Sort(nums);
Console.Write("Sorted order: ");
foreach(int i in nums){
Console.Write(i + " ");
}
Console.WriteLine();
}
}
The code above generates the following result.
Sort than binary search
using System; //j av a 2s . co m
class MainClass {
public static void Main() {
int[] nums = { 5, 4, 6, 3, 14, 9, 8, 17, 1, 24, -1, 0 };
Array.Sort(nums);
// Search for 14.
int idx = Array.BinarySearch(nums, 14);
Console.WriteLine("Index of 14 is " + idx);
}
}
The code above generates the following result.
Sort cusomized types
using System;/*j ava 2s . co m*/
public class Employee: IComparable{
public Employee(string name, int id)
{
this.name = name;
this.id = id;
}
int IComparable.CompareTo(object obj)
{
Employee emp2 = (Employee) obj;
if (this.id > emp2.id)
return(1);
if (this.id < emp2.id)
return(-1);
else
return(0);
}
public override string ToString()
{
return(String.Format("{0}:{1}", name, id));
}
string name;
int id;
}
class MainClass
{
public static void Main()
{
Employee[] arr = new Employee[4];
arr[0] = new Employee("A", 1);
arr[1] = new Employee("B", 2);
arr[2] = new Employee("C", 4);
arr[3] = new Employee("D", 3);
Array.Sort(arr);
foreach (Employee emp in arr)
Console.WriteLine("Employee: {0}", emp);
Console.WriteLine("Find employee id 2 in the list");
Employee employeeToFind = new Employee(null, 2);
int index = Array.BinarySearch(arr, employeeToFind);
if (index != -1)
Console.WriteLine("Found: {0}", arr[index]);
}
}
The code above generates the following result.
Array.Sort by CultureInfo
using System;/*from jav a2 s . c o m*/
using System.Globalization;
class Program {
static void DisplayNames(IEnumerable e) {
foreach (string s in e)
Console.Write(s + " - ");
}
static void Main(string[] args) {
string[] names = {"Alabama", "Texas", "Washington",
"Virginia", "Wisconsin", "Wyoming",
"Kentucky", "Missouri", "Utah", "Hawaii",
"Kansas", "Lousiana", "Alaska", "Arizona"};
Thread.CurrentThread.CurrentCulture = new CultureInfo("fi-FI");
Array.Sort(names);
DisplayNames(names);
Array.Sort(names, Comparer.DefaultInvariant);
Console.WriteLine("\nsorted with invariant culture...");
DisplayNames(names);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Array