Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- public class Sorting
- {
- public static void Main()
- {
- Random rand = new Random();
- Stopwatch sw = new Stopwatch();
- int[] array1 = new int[10000];
- int[] array2 = new int[10000];
- int[] array3 = new int[10000];
- int[] array4 = new int[10000];
- // Feltöltés
- for (int i = 0; i < array1.Length; i++)
- {
- array1[i] = array2[i] = array3[i] = array4[i] = rand.Next(Int32.MinValue, Int32.MaxValue);
- }
- // Quicksort
- sw.Start();
- UnsafeQuickSort(array1);
- sw.Stop();
- Console.WriteLine("========= Quicksort\nElapsed time on a random array (size = 10000): = {0}",sw.Elapsed);
- sw.Reset();
- sw.Start();
- UnsafeQuickSort(array1);
- sw.Stop();
- Console.WriteLine("Elapsed time on a sorted array (size = 10000): = {0}",sw.Elapsed);
- sw.Reset();
- Console.WriteLine();
- // Insertion sort
- sw.Start();
- InsertionSort(array2);
- sw.Stop();
- Console.WriteLine("========= Insertion sort\nElapsed time on a random array (size = 10000): = {0}",sw.Elapsed);
- sw.Reset();
- sw.Start();
- InsertionSort(array2);
- sw.Stop();
- Console.WriteLine("Elapsed time on a sorted array (size = 10000): = {0}",sw.Elapsed);
- sw.Reset();
- Console.WriteLine();
- // Bubble sort
- sw.Start();
- BubbleSort(array3);
- sw.Stop();
- Console.WriteLine("========= Bubble sort\nElapsed time on a random array (size = 10000): = {0}",sw.Elapsed);
- sw.Reset();
- sw.Start();
- BubbleSort(array3);
- sw.Stop();
- Console.WriteLine("Elapsed time on a sorted array (size = 10000): = {0}",sw.Elapsed);
- sw.Reset();
- }
- public static void InsertionSort(int[] data)
- {
- for (int i = 0; i < data.Length - 1; i++)
- {
- for (int j = i + 1; j > 0; j--)
- {
- if (data[j - 1] < data[j])
- {
- int temp = data[j - 1];
- data[j - 1] = data[j];
- data[j] = temp;
- }
- }
- }
- }
- public static void BubbleSort(int[] data)
- {
- for(int i=0; i < data.Length; i++){
- for(int j=1; j < (data.Length-i); j++){
- if(data[j-1] < data[j]){
- //swap elements
- int temp = data[j-1];
- data[j-1] = data[j];
- data[j] = temp;
- }
- }
- }
- }
- public unsafe static void UnsafeQuickSort(int[] data)
- {
- fixed (int* pdata = data)
- {
- UnsafeQuickSortRecursive(pdata, 0, data.Length - 1);
- }
- }
- private unsafe static void UnsafeQuickSortRecursive(int* data, int left, int right)
- {
- int i = left - 1;
- int j = right;
- while (true)
- {
- int d = data[left];
- do i++; while (data[i] < d);
- do j--; while (data[j] > d);
- if (i < j)
- {
- int tmp = data[i];
- data[i] = data[j];
- data[j] = tmp;
- }
- else
- {
- if (left < j) UnsafeQuickSortRecursive(data, left, j);
- if (++j < right) UnsafeQuickSortRecursive(data, j, right);
- return;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement