I am using selection sort in GUI and the thing is that when I select selection sort and do sorting on generate numbers it sorts generated numbers for one time but if next time I will use other number it will do just the first step of sorting by just replacing two numbers and won't work then... So why it's not working again and why showing such different behavior?
The code is:-
void SelectionSort() {
int i = 0;
int j, min, temp;
min = i;
for (j = i + 1; j < 10; j++) {
if (generate[min] > generate[j]) {
min = j;
}
}
if (min != i) {
temp = generate[i];
generate[i] = generate[min];
generate[min] = temp;
//show1(generate);
}
show1(generate);
i++;
}
My guess, you need to add i=0; at the beginning.
I guess from your function that i is a global variable.
You need to reset i to 0 every time you enter the function (Inside the function)
using System;
namespace SelectionSortExample
{
class Program
{
static void Main(string[] args)
{
int[] num = { 105, 120, 10, 200, 20 };
for (int i = 0; i < num.Length; i++)
{
int minIndex = i;
for (int j = i + 1; j < num.Length; j++)
{
if (num[minIndex] > num[j])
{
minIndex = j;
}
}
int tmp = num[i];
num[i] = num[minIndex];
num[minIndex] = tmp;
}
}
}
}
Related
i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}
I am working on a project that compares the time bubble and selection sort take. I made two separate programs and combined them into one and now bubble sort is running much faster than selection sort. I checked to make sure that the code wasn't just giving me 0s because of some conversion error and was running as intended. I am using System.Diagnostics; to measure the time. I also checked that the machine was not the problem, I ran it on Replit and got similar results.
{
class Program
{
public static int s1 = 0;
public static int s2 = 0;
static decimal bubblesort(int[] arr1)
{
int n = arr1.Length;
var sw1 = Stopwatch.StartNew();
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr1[j] > arr1[j + 1])
{
int tmp = arr1[j];
// swap tmp and arr[i] int tmp = arr[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = tmp;
s1++;
}
}
}
sw1.Stop();
// Console.WriteLine(sw1.ElapsedMilliseconds);
decimal a = Convert.ToDecimal(sw1.ElapsedMilliseconds);
return a;
}
static decimal selectionsort(int[] arr2)
{
int n = arr2.Length;
var sw1 = Stopwatch.StartNew();
// for (int e = 0; e < 1000; e++)
// {
for (int x = 0; x < arr2.Length - 1; x++)
{
int minPos = x;
for (int y = x + 1; y < arr2.Length; y++)
{
if (arr2[y] < arr2[minPos])
minPos = y;
}
if (x != minPos && minPos < arr2.Length)
{
int temp = arr2[minPos];
arr2[minPos] = arr2[x];
arr2[x] = temp;
s2++;
}
}
// }
sw1.Stop();
// Console.WriteLine(sw1.ElapsedMilliseconds);
decimal a = Convert.ToDecimal(sw1.ElapsedMilliseconds);
return a;
}
static void Main(string[] args)
{
Console.WriteLine("Enter the size of n");
int n = Convert.ToInt32(Console.ReadLine());
Random rnd = new System.Random();
decimal bs = 0M;
decimal ss = 0M;
int s = 0;
int[] arr1 = new int[n];
int tx = 1000; //tx is a variable that I can use to adjust sample size
decimal tm = Convert.ToDecimal(tx);
for (int i = 0; i < tx; i++)
{
for (int a = 0; a < n; a++)
{
arr1[a] = rnd.Next(0, 1000000);
}
ss += selectionsort(arr1);
bs += bubblesort(arr1);
}
bs = bs / tm;
ss = ss / tm;
Console.WriteLine("Bubble Sort took " + bs + " miliseconds");
Console.WriteLine("Selection Sort took " + ss + " miliseconds");
}
}
}
What is going on? What is causing bubble sort to be fast or what is slowing down Selection sort? How can I fix this?
I found that the problem was that the Selection Sort was looping 1000 times per method run in addition to the 1000 runs for sample size, causing the method to perform significantly worse than bubble sort. Thank you guys for help and thank you TheGeneral for showing me the benchmarking tools. Also, the array that was given as a parameter was a copy instead of a reference, as running through the loop manually showed me that the bubble sort was doing it's job and not sorting an already sorted array.
To solve your initial problem you just need to copy your arrays, you can do this easily with ToArray():
Creates an array from a IEnumerable.
ss += selectionsort(arr1.ToArray());
bs += bubblesort(arr1.ToArray());
However let's learn how to do a more reliable benchmark with BenchmarkDotNet:
BenchmarkDotNet Nuget
Official Documentation
Given
public class Sort
{
public static void BubbleSort(int[] arr1)
{
int n = arr1.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr1[j] > arr1[j + 1])
{
int tmp = arr1[j];
// swap tmp and arr[i] int tmp = arr[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = tmp;
}
}
}
}
public static void SelectionSort(int[] arr2)
{
int n = arr2.Length;
for (int x = 0; x < arr2.Length - 1; x++)
{
int minPos = x;
for (int y = x + 1; y < arr2.Length; y++)
{
if (arr2[y] < arr2[minPos])
minPos = y;
}
if (x != minPos && minPos < arr2.Length)
{
int temp = arr2[minPos];
arr2[minPos] = arr2[x];
arr2[x] = temp;
}
}
}
}
Benchmark code
[SimpleJob(RuntimeMoniker.Net50)]
[MemoryDiagnoser()]
public class SortBenchmark
{
private int[] data;
[Params(100, 1000)]
public int N;
[GlobalSetup]
public void Setup()
{
var r = new Random(42);
data = Enumerable
.Repeat(0, N)
.Select(i => r.Next(0, N))
.ToArray();
}
[Benchmark]
public void Bubble() => Sort.BubbleSort(data.ToArray());
[Benchmark]
public void Selection() => Sort.SelectionSort(data.ToArray());
}
Usage
static void Main(string[] args)
{
BenchmarkRunner.Run<SortBenchmark>();
}
Results
Method
N
Mean
Error
StdDev
Bubble
100
8.553 us
0.0753 us
0.0704 us
Selection
100
4.757 us
0.0247 us
0.0231 us
Bubble
1000
657.760 us
7.2581 us
6.7893 us
Selection
1000
300.395 us
2.3302 us
2.1796 us
Summary
What have we learnt? Your bubble sort code is slower ¯\_(ツ)_/¯
It looks like you're passing in the sorted array into Bubble Sort. Because arrays are passed by reference, the sort that you're doing on the array is editing the same contents of the array that will be eventually passed into bubble sort.
Make a second array and pass the second array into bubble sort.
Okay I'm having a problem with the selection sort algorithm. It'll sort ints just fine but when I try to use it for doubles it starts to sort randomly.
here's my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sorter.ListSort;
using System.Collections;
namespace ConsoleApp20
{
class Program
{
static void Main(string[] args)
{
var x = new List<double>();
x.Add(23.1);
x.Add(1.5);
x.Add(3);
x.Add(15.23);
x.Add(101.2);
x.Add(23.35);
var sorted = selectionSort(x);
foreach (double s in sorted)
Console.WriteLine(s);
Console.ReadLine();
}
public static List<double> selectionSort(List<double> data)
{
int count = data.Count;
// Console.WriteLine(count);
for (int i = 0; i < count - 1; i++)
{
int min = i;
for (int j = i + 1; j < count; j++)
{
if (data[j] < data[min])
min = j;
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
return data;
}
}
}
Now this is what the algorithm is returning
As we can see 3 is NOT bigger than 15.23, what's going on?
Like MoreON already mentioned in the comments, you should swap the elements after you've found the min value.
So it should look like this
public static List<double> selectionSort(List<double> data)
{
int count = data.Count;
// Console.WriteLine(count);
for (int i = 0; i < count - 1; i++)
{
int min = i;
for (int j = i + 1; j < count; j++)
{
if (data[j] < data[min])
min = j;
}
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
return data;
}
But if you don't want to reinvent the wheel, you could also use:
var sorted = x.OrderBy(o => o).ToList();
You need to change place for int min
for (int i = 0; i < count - 1; i++)
{
for (int j = i + 1; j < count; j++)
{
int min = i;
if (data[j] < data[min])
min = j;
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
Add a new method called swap and use the following selection sort code.
void swap(int *a,int*b){
int temp=*a;
*a=*b;
*b=temp;
}
void selectionSort(int arr[],int n){
int min_index;
for(int i=0;i<n-1;i++)
{
min_index=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
min_index=j;
}
swap(&arr[min_index],&arr[i]);
}
}
I am will be grateful for help because I am not sure how make this program.
I should code program with two tables. The first will fill it with numbers Random tab = new Random();. After that I should reverse numbers and fill them into second table.
I made first functionality but I am not sure how make start with second table?
class Program
{
static void Main(string[] args)
{
int[] tablica1 = new int[20];
Random tab = new Random();
for (int i = 0; i < 20; i++)
{
tablica1[i] = tab.Next(20);
Console.WriteLine("Tablica wylosowała nastepujace elementy:");
Console.WriteLine(tablica1[i]);
}
Console.Read();
int[] tablica2 = new int[20];
/*for (int i = 20; i > 0; i--)
{
}
*/
}
}
You didn't quite describe what exactly happens when you run the code, but I think the problem is with this part - as this should give you an IndexOutOfRangeException:
for (int j = tablica2.Length; j > 1 ; j--)
{
tablica2[j] = tablica1[20-j];
Console.WriteLine(tablica2[j]);
}
The array indices go form 0 to tablica2.Length - 1 (one less then the length, so the index tablica2.Length is outside the array).
Your loop goes in reverse from tablica2.Length two 2 for some reason.
So as soon as it starts executing, j is 20, but the highest index is 19.
Change the loop so it goes the full range, and change the loop body so that you don't access out-of-range indices, in one of two ways:
for (int j = tablica2.Length - 1; j >= 0 ; j--) // goes from 19 to 0
{
tablica2[j] = tablica1[tablica1.Length - j - 1];
}
or
for (int j = tablica2.Length; j > 0 ; j--) // goes from 20 to 1
{
tablica2[j - 1] = tablica1[tablica1.Length - j];
}
static void Main(string[] args)
{
int[] tablica1 = new int[20];
Random tab = new Random();
for (int i = 0; i < 20; i++)
{
tablica1[i] = tab.Next(20);
Console.WriteLine("Tablica wylosowała nastepujace elementy:");
Console.WriteLine(tablica1[i]);
}
Console.Read();
int[] tablica2 = new int[20];
for (int i = 20; i > 0; i--)
{
tablica2[i]=tablica1[20-i];
}
}
}
#Sinatr Thank You for this topic. It was really helpful but there is only one table.
#Filip Milovanović Yes, I have to make two two tables :) After reserving first, I should put elements from first to second. I changed this for, but in console I am still able to see only first one. :(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Randomy1
{
class Program
{
static void Main(string[] args)
{
int[] tablica1 = new int[20];
Random tab = new Random();
for (int i = 0; i < 20; i++)
{
tablica1[i] = tab.Next(20);
Console.WriteLine(tablica1[i]);
}
int[] tablica2 = new int[20];
for (int j = tablica2.Length; j > 1 ; j--)
{
tablica2[j] = tablica1[20-j];
Console.WriteLine(tablica2[j]);
}
Console.Read();
}
}
}
I think this would work
for (int i = 0; i < 20; i++)
{
tablica2[i] = tablica1[20 - (i + 1)];
Console.WriteLine("Tablica 1st :: " + tablica1[i] + " Tablica 1 Reverse " + tablica1[20 - (i + 1)] + " Tablica 2 " + tablica2[i]);
}
My program is messed up bad, and I need help!
I already tried c++, and c# is new for me. Experts here at the university said that c# is like c++, and so I tried to widen my perspective on other programming languages other that c++. I tried to make a program that computes the sum of the lowest 3 numbers in 5 inputted numbers on windows application.
to view the design of the windows application is here:
Design View
and my messed up code:
namespace Array_excercise
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] nums = { 0, 0, 0, 0, 0 };
int[] lownum = { 0, 0, 0,0,0 };
int[] highnum = { 0, 0, 0, 0, 0 };
private void computbtn_Click(object sender, EventArgs e)
{
nums[0] = Int32.Parse(textBox1.Text);
nums[1] = Int32.Parse(textBox2.Text);
nums[2] = Int32.Parse(textBox3.Text);
nums[3] = Int32.Parse(textBox4.Text);
nums[4] = Int32.Parse(textBox5.Text);
int result;
for (int a = 0; a <= 4; a++)
{
if (nums[a] < nums[0])
lownum[a] = nums[a];
else if (nums[a] < nums[1])
lownum[a] = nums[a];
else if (nums[a] < nums[2])
lownum[a] = nums[a];
else if (nums[a] < nums[3])
lownum[a] = nums[a];
else if (nums[a] < nums[4])
lownum[a] = nums[a];
else
highnum[a] = nums[a];
}
}
}
After that, I don't know how to compute the sum.
for now, I'm particularly learning how to use arrays with if and for loop functions.
I'll be very grateful if those functions are used in this program.
I thank you in advance!
Use LINQ
var lowSum = nums.OrderBy(n => n).Take(3).Sum();
A one-dimensional array can be sorted with the static Sort() method.
https://msdn.microsoft.com/en-us/library/system.array.sort(v=vs.110).aspx
So in your example, it would go something like:
// populate the array
nums[0] = Int32.Parse(textBox1.Text);
nums[1] = Int32.Parse(textBox2.Text);
nums[2] = Int32.Parse(textBox3.Text);
nums[3] = Int32.Parse(textBox4.Text);
nums[4] = Int32.Parse(textBox5.Text);
// sort the array from lowest to highest
Array.Sort(nums);
// declare a variable to hold the sum
int sum = 0;
// iterate over the first (smallest) three
for(int i=0;i<3; i++)
{
sum += nums[i];
}
Console.WriteLine("The sum of the three smallest is: " + sum);
Try with some sorting algorithms, for example bubble sort to sort your array:
int c = -1;
for (int i = array.Length; i > 1; i--)
{
for (int j = 0; j < i - 1; j++)
{
c = j;
if (array[j] < array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
After you have the sorted array, you can get the sum of the first 3 lowest number:
int sum = 0;
for(int i=0; i < 3; i++)
{
sum += array[i];
}
After putting all the values into "nums". You can set the values of the two arrays using the following code.
List<int> tempnums = nums.ToList(); //Creates a List from "nums" array.
tempnums.Sort(); //Sorts the List from smallest number to highest
int[] lownums = tempnums.ToArray(); //Creates an array from "tempnums" List.
tempnums.Reverse();//Reverses the values of "tempnums" so that the numbers are highest to lowest.
int[] highnums = tempnums.ToArray();//Creates an array from "tempnums" List.
And then there are two ways to get the result.
int result = 0;
for(int i = 1; i <= 3; i++)
{
result += nums[i];
}
Or
int result = nums[0]+nums[1]+nums[2];