C#, I'm trying to create an array in a class as an object. I want this program to run the method when I do the bubble sort. I need to understand how to pass the value from the decimal array, already created from text to this object? I got something wrong somewhere. All I'm getting is the name of the form when I print out the array on the other side of front end of the form.
main form using call to class: Sort sort = new Sort(rawArray);
using System;
namespace GthrBbblSrtProj
{
public class Sort
{
private decimal[] theArray;
public Sort() { }
public Sort (decimal[] sort)
{
this.theArray = sort;
}
public decimal[] TheArray
{
get
{
return theArray;
}
set
{
theArray = value;
}
}
//Sort Method: Bubble Sort
public Array SortingMethod()
{
for (int i = 0; i <= TheArray.Length - 1; i )
{
// Temp int variable to hold value in
decimal temp;
// Swap out adjacent value by order,
// till completed.
for (int j = 0; j < TheArray.Length - 1; j )
{
if (TheArray[j] > TheArray[j 1])
{
temp = TheArray[j 1];
TheArray[j 1] = TheArray[j];
TheArray[j] = temp;
}
}
}
return TheArray;
}
}
}
CodePudding user response:
As I can see, you are looking for a inplace bubble sort; if it's your case I suggest a different (generalized) design:
public class ArraySort {
// Generic array (not necessary decimal one)
// Generic way of sorting (we can specify our own comparer)
public static T[] BubbleSort<T>(this T[] array, IComparer<T> comparer = null) {
// Input paramers validation
if (null == array)
throw new ArgumentNullException(nameof(array));
// If no comparer provided, we try using default one,
// if no default comparer has been found, we complain
if (null == (comparer ??= Comparer<T>.Default))
throw new ArgumentNullException(nameof(comparer),
$"No default comparer for {typeof(T).Name} class");
// Your algorithm a bit refined
for (int i = 0; i < array.Length; i )
for (int j = 0; j < array.Length - 1; j )
if (comparer.Compare(array[j], array[j 1]) > 0)
(array[j], array[j 1]) = (array[j 1], array[j]); // <- swap
return array;
}
}
Now you can put either
ArraySort.BubbleSort(array);
Or
array = ArraySort.BubbleSort(array);
Or even
array.BubbleSort();
Demo:
decimal[] array = ArraySort.BubbleSort(new decimal[] { 3, 5, 2, 1, 4});
Console.Write(string.Join(", ", array));
Outcome:
1, 2, 3, 4, 5
CodePudding user response:
You need a class with a decimal array as a property and a method that sorts the array for your homework? That's my best guess from what you wrote... If that's the case:
public class SortingClass
{
public decimal[] TheArray { get; set; }
public void Sort()
{
// Do the sort
}
}
Then you set the array and you call the method:
var sortingClass = new SortingClass();
sortingClass.TheArray = YourArray;
sortingClass.Sort();
But are you sure that's what the homework wants you to do? Because i don't see any reason for the array property in the class. Anyway, you should share more details about what you get wrong, if you want people to be able to help you.