Selection sort in typescript

Ts program for Selection sort. Here more solutions.

/*
  TypeScript program for selection sort
*/
class MySort
{
	// Swap the array element
	public swap(arr: number[], x: number, y: number)
	{
		// x and y are index of array
		var temp = arr[x];
		arr[x] = arr[y];
		arr[y] = temp;
	}
	public selectionSort(arr: number[], n: number)
	{
		var min = 0;
		// Execute loop from 0..n
		for (var i = 0; i < n; ++i)
		{
			// Get current index
			min = i;
			for (var j = i + 1; j < n; ++j)
			{
				if (arr[min] > arr[j])
				{
					// Get the minimum element index
					min = j;
				}
			}
			if (i != min)
			{
				// Swap minimum element at i index
				this.swap(arr, i, min);
			}
		}
	}

	public display(arr: number[])
	{
		
		console.log(" ",arr);
	}
	public static main()
	{
		var task = new MySort();
		// Array of integer elements
		var arr: number[] = [8, 2, 3, 8, 1, 3, 73, 121, 
                             54, 23, 84, 13, 67, 23, 52];
		// Get the size of array
		var n = arr.length;
		console.log(" Before Sort :");
		task.display(arr);
		// Test
		task.selectionSort(arr, n);
		console.log(" After Sort :");
		task.display(arr);
	}
}
MySort.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

 Before Sort :
  [ 8, 2, 3, 8, 1, 3, 73, 121, 54, 23, 84, 13, 67, 23, 52 ]
 After Sort :
  [ 1, 2, 3, 3, 8, 8, 13, 23, 23, 52, 54, 67, 73, 84, 121 ]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved