我是演算法的新手,我試圖寫一個選擇排序。在互聯網的幫助下,我有一個應該可以作業的腳本,但沒有。sort 方法之后的結果是一個仍未排序的串列。
我不確定我是否遺漏了什么,我的代碼看起來和網上的一樣。
產品.cs
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
}
訂單.cs
public class Order
{
public List<Product> listOfProducts = new List<Product>(){
new Product(){ Name="Item1", Price=2.55 },
new Product(){ Name="Item2", Price=1.92 },
new Product(){ Name="Item3", Price=2.12 }
};
public List<Product> GetAllProducts(){
return this.listOfProducts;
}
public void SortProductsByPrice(){
int min = 0;
for (int i = 0; i < this.listOfProducts.Count - 1; i )
{
min = i;
for (int j = 0; j < this.listOfProducts.Count; j )
{
if (listOfProducts[j].Price < listOfProducts[min].Price)
{
min = j;
}
}
Product temporary = listOfProducts[min];
listOfProducts[min] = listOfProducts[i];
listOfProducts[i] = temporary;
}
}
}
程式.cs
static void Main(string[] args)
{
Order order = new Order();
// unsorted list
foreach (Product pro in order.GetAllProducts())
{
Console.WriteLine(pro.Price);
}
Console.WriteLine("------------------------------------------");
order.SortProductsByPrice();
// sorted list
foreach (Product pro in order.GetAllProducts())
{
Console.WriteLine(pro.Price);
}
Console.ReadLine();
}
uj5u.com熱心網友回復:
您的代碼中的問題出在嵌套回圈中。
如果您仔細查看演算法,您會發現:
選擇排序是一種簡單的排序演算法。該排序演算法是一種基于就地比較的演算法,其中串列分為兩部分,左端的排序部分和右端的未排序部分。最初,已排序的部分是空的,未排序的部分是整個串列。
您正在將您的值與您已經排序的值重新比較,這是您不應該做的。您沒有得到一個排序串列,因為在您的代碼結束時,這些值被一遍又一遍地交換,直到它們恢復到原來的順序。一個簡單的解決方法是更改??嵌套的 for 回圈,如下所示:
public void SortProductsByPrice()
{
int min = 0;
for (int i = 0; i < this.listOfProducts.Count - 1; i )
{
min = i;
for (int j = i 1; j < this.listOfProducts.Count; j )
{
if (listOfProducts[j].Price < listOfProducts[min].Price)
{
min = j;
}
}
Product temporary = listOfProducts[min];
listOfProducts[min] = listOfProducts[i];
listOfProducts[i] = temporary;
}
}
準確地說,我們只更改了 1 行:
for (int j = i 1; j < this.listOfProducts.Count; j )
^^^^^
如果你再看一下上面鏈接中的偽代碼,你會發現這個函式現在類似于它:
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
/* check the element to be minimum */
for j = i 1 to n
if list[j] < list[min] then
min = j;
end if
end for
/* swap the minimum element with the current element*/
if indexMin != i then
swap list[min] and list[i]
end if
end for
end procedure
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441064.html
上一篇:按兩個條件(名稱序列和日期)對字串陣列進行排序/排序-JavaScript
下一篇:根據地圖中的值對串列進行排序
