Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming in C# SortMyArray Write a function that takes in an array of integer

ID: 3709764 • Letter: P

Question

Programming in C#

SortMyArray

Write a function that takes in an array of integers and sorts the array from smallest to largest. Your function should return an array with the sorted list and print the list out. You can assume that the array being passed will always have integers (You do not need to type check the array). DO NOT USE the built-in array sort function.

Output sample:

var arr1=[-3,8,7,6,5,-4,3,2,1];

SortMyArray(arr1);

[ -4, -3, 1, 2, 3, 5, 6, 7, 8 ]

var test_array=[1,2,3,4,5];

SortMyArray(test_array);

[ 1,2,3,4,5]

var test_array=[];

SortMyArray(test_array);

Cannot sort an Empty Array!

var test_array=[1,-1,-2,2,3,-3,-4,4,5,-5,0];

SortMyArray(test_array);

[ -5,-4,-3,-2,-1,0,1,2,3,4,5]

var test_array=[1, 1, 1, 100, 75, 2, 2, 37, 55, 55];

SortMyArray(test_array);

[1,1,1,2,2,37,55,55,75,100]

Explanation / Answer

using System.IO;

using System;

class Program

{

static void Main()

{

int[] arr1={-3,8,7,6,5,-4,3,2,1};

SortMyArray(arr1);

for(int i=0;i<arr1.Length;i++) {

Console.Write(arr1[i]+" ");

}

Console.WriteLine();

}

static void SortMyArray(int[] array) {

int n = array.Length;

int temp;

for (int i = 0; i < n; i++) {

int j = 1;

while (j < (n - i)) {

if (array[j - 1] > array[j]) {

// swap the elements!

temp = array[j - 1];

array[j - 1] = array[j];

array[j] = temp;

}

j++;

}

}

}

}

Output: