کپی کردن یک آرایه در آرایه دیگر با متد CopyTo از کلاس Array
کد:
using System;
public class CopyToArray
{
public static void Main()
{
object[] objects1 = {"one", "two", "three"};
object[] objects2 = {0, 1, 2, 3, 4, 5};
Console.Write ("objects1 array elements: ");
foreach(object o in objects1)
{
Console.Write ("{0} ", o);
}
Console.Write ("nobjects2 array elements: ");
foreach (object o in objects2)
{
Console.Write ("{0} ", o);
}
objects1.CopyTo (objects2, 1);
Console.Write ("nobjects2 array elements: ");
foreach (object o in objects2)
{
Console.Write ("{0} ", o);
}
Console.WriteLine();
}
}
اینم از الگوریتم مرتب سازی سریع (Quick Sort) همینجا میزارم که تو پست های دیگه قاطی نشه
کد:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Quicksort
{
class Program
{
static void Main(string[] args)
{
// Create an unsorted array of string elements
string[] unsorted = { "z", "e", "x", "c", "m", "q", "a" };
// Print the unsorted array
for (int i = 0; i < unsorted.Length; i++)
{
Console.Write(unsorted[i] + " ");
}
Console.WriteLine();
// Sort the array
Quicksort(unsorted, 0, unsorted.Length - 1);
// Print the sorted array
for (int i = 0; i < unsorted.Length; i++)
{
Console.Write(unsorted[i] + " ");
}
Console.WriteLine();
Console.ReadLine();
}
public static void Quicksort(IComparable[] elements, int left, int right)
{
int i = left, j = right;
IComparable pivot = elements[(left + right) / 2];
while (i <= j)
{
while (elements[i].CompareTo(pivot) < 0)
{
i++;
}
while (elements[j].CompareTo(pivot) > 0)
{
j--;
}
if (i <= j)
{
// Swap
IComparable tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
i++;
j--;
}
}
// Recursive calls
if (left < j)
{
Quicksort(elements, left, j);
}
if (i < right)
{
Quicksort(elements, i, right);
}
}
}
}
خروجی :
z e x c m q a
a c e m q x z