C#,我試圖在類中創建一個陣列作為物件。我希望這個程式在我進行冒泡排序時運行該方法。我需要了解如何將已從文本創建的十進制陣列中的值傳遞給此物件?我在某處出錯了。當我在表單前端的另一側列印出陣列時,我得到的只是表單的名稱。
使用類呼叫的主要形式: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;
}
}
}
uj5u.com熱心網友回復:
如我所見,您正在尋找就地冒泡排序;如果是您的情況,我建議采用不同的(通用)設計:
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;
}
}
現在你可以把
ArraySort.BubbleSort(array);
或者
array = ArraySort.BubbleSort(array);
甚至
array.BubbleSort();
演示:
decimal[] array = ArraySort.BubbleSort(new decimal[] { 3, 5, 2, 1, 4});
Console.Write(string.Join(", ", array));
結果:
1, 2, 3, 4, 5
uj5u.com熱心網友回復:
您需要一個以十進制陣列作為屬性的類和一個為您的家庭作業對陣列進行排序的方法嗎?這是我對你寫的最好的猜測......如果是這樣的話:
public class SortingClass
{
public decimal[] TheArray { get; set; }
public void Sort()
{
// Do the sort
}
}
然后設定陣列并呼叫該方法:
var sortingClass = new SortingClass();
sortingClass.TheArray = YourArray;
sortingClass.Sort();
但是你確定這就是作業要你做的嗎?因為我沒有看到類中陣列屬性的任何原因。無論如何,如果你希望人們能夠幫助你,你應該分享更多關于你犯錯的細節。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385970.html
上一篇:如何使用來自任意型別類的變數?
