Bubble Sort Example
Bubble Sort Example
namespace Thread1 { class BubbleSort { int[] array; public BubbleSort(int[] array1) { array = array1; } private void swap(int[] arr, int i, int j) { int e = arr[i]; arr[i] = arr[j]; arr[j] = e; } public void Sort() { Console.WriteLine(Thread.CurrentThread.Name + ": started"); for (int i = 0; i < array.Length; i++) { for (int j = array.Length - 1; j > i; j--) if (array[j] < array[j - 1]) swap(array, j-1, j); if (i%1000 == 0) Console.WriteLine(Thread.CurrentThread.Name + ": is executing"); } Console.WriteLine(Thread.CurrentThread.Name + ": completed"); } } class ThreadDriver { static void Main(string[] args) { Console.WriteLine("The main thread: started"); // Random object used Random rand1 = new Random(); int[] arr1 = new int[10000]; int[] arr2 = new int[10000]; for (int i = 0; i < arr1.Length; i++) { arr1[i] = rand1.Next(); arr2[i] = rand1.Next(); } BubbleSort bb1 = new BubbleSort(arr1); BubbleSort bb2 = new BubbleSort(arr2); //Thread th1 = new Thread(new ThreadStart(bb1.Sort)); or simply Thread th1 = new Thread(bb1.Sort); th1.Name = "thread1"; Thread th2 = new Thread(bb2.Sort); th2.Name = "thread2";
th1.Start(); th2.Start(); // print a part of arr1 here, is it sorted? //for (int i = 0; i < 100; i++) // Console.WriteLine("arr[{0}]= {1}", i, arr1[i]); Console.WriteLine("The main thread: completed"); } } }
You can compile the program from command line E:\examples>csc ThreadDriver.cs Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved. E:\examples>ThreadDriver.exe The main thread: started The main thread: completed thread1: started thread1: is executing thread2: started thread2: is executing thread1: is executing thread2: is executing thread2: is executing thread1: is executing thread2: is executing thread1: is executing thread2: is executing thread1: is executing thread2: is executing thread1: is executing thread2: is executing thread1: is executing thread2: is executing thread1: is executing thread2: is executing thread1: is executing thread2: is executing thread2: completed thread1: is executing thread1: completed