2017-03-15 1 views
-2
struct SSales 
    { 
     private int Y; 
     private double S; 

     public int Year 
     { 
      get { return Y; } 
      set { Y = value; } 

     } 
     public double Sale 
     { 
      get { return S; } 
      set { S = value; } 
     } 

     public SSales (int _year, double _sales) 
     { 

      Y = _year; 
      S = _sales; 

     } 

private void Sortbutton_Click(object sender, EventArgs e) 
    { 
     listBox1.Items.Clear(); 
     if (yearradio.Checked) 
     { 
      int temp = 0; 
      for (int i = 0; i < bubble.Length - 1; i++) 
      { 
       for (int j = 0; j < bubble.Length - 1; j++) 
       { 
        if (bubble[i + 1].Year < bubble[i].Year) 
        { 
         temp = bubble[i].Year; 
         bubble[i].Year = bubble[i + 1].Year; 
         bubble[i + 1].Year = temp; 
        } 
       } 
      } 

     } 
     if (salesradio.Checked) 
     { 
      double temp2 = 0; 
      for (int i = 0; i < bubble.Length - 1; i++) 
      { 
       for (int j = 0; j < bubble.Length - 1; j++) 
       { 
        if (bubble[i + 1].Sale > bubble[i].Sale) 
        { 
         temp2 = bubble[i].Sale; 
         bubble[i].Sale = bubble[i + 1].Sale; 
         bubble[i + 1].Sale = temp2; 

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

      listBox1.Items.Add(bubble[i].ToString()); 

     } 

    } 

거품 형 정렬 알고리즘은 완벽하게 작동하지만 정렬 버튼을 클릭 할 때마다 점진적으로 만 정렬됩니다. 1 번 클릭으로 목록 상자를 완전히 정렬해야합니다. 내 코드는 지금처럼구조체 멤버를 사용할 때 거품 정렬

enter image description here

또한, 년간 및 판매는 서로 완전히 독립적으로 재구성. 판매 지표가 변경되면 해당 연도 지수는 동일한 위치에 유지되고 반대의 경우도 마찬가지입니다.

int for 루프가 작동하는 것으로 추측하고 있지만이를 구현하는 방법을 잘 모르겠습니다. 어떤 도움을 주시면 감사하겠습니다!

답변

0

학습/실습을위한 버블 정렬을 수행하고 있다고 생각합니다. 그렇지 않다면 inbuilt Array.Sort() 또는 Enumerable.OrderBy() 또는 비슷한 것을 사용해야합니다.

잘못 수행 한 여러 가지 사항이 있습니다. 나는 당신이 직면하고있는 문제를 명확히

struct SSales { 
    public int Year { get; set; } // use auto-properties for brevity 

    public double Sale { get; set; } // use auto-properties for brevity 

    public SSales(int year, double sales) { 
     Year = year; 
     Sale = sales; 
    } 
} 

// Use a generic routine to Swap, instead of replicating the code multiple times 
// Note that we are passing by reference so the actual array eventually gets sorted 
// Also, don't swap the properties, but the whole record. Else it will corrupt your data 
static void Swap<T>(ref T obj1, ref T obj2) { 
    var temp = obj1; 
    obj1 = obj2; 
    obj2 = temp; 
} 

// Write the sort routine separately. Sorts usually just need a way to compare records, which can be provided by Caller (IoC pattern) 
static void Sort<T>(T[] items, Func<T, T, int> comparer) { 
    for (int i = 0; i < items.Length - 1; i++) { 
     // Every execution of the inner loop will bubble-up the largest element in the range 
     // Your array is getting sorted from the end, so you don't need to re-compare the already sorted part 
     for (int j = 0; j < items.Length - 1 - i; j++) { 
      if (comparer(items[j], items[j + 1]) > 0) // call the generic user provided comparer to know the sequence 
       Swap(ref items[j], ref items[j + 1]); // use teh generic swapper to swap elements in the array 
     } 
    } 
} 


private void Sortbutton_Click(object sender, EventArgs e) { 
    listBox1.Items.Clear(); 

    if (yearradio.Checked) { 
     // Invoke the Sort routine, with the required comparer 
     Sort(bubble, (a, b) => a.Year - b.Year); 
    } 

    if (salesradio.Checked) { 
     // Invoke the Sort routine, with the required comparer 
     Sort(bubble, (a, b) => (int)(a.Sale - b.Sale)); 
    } 

    for (int i = 0; i < bubble.Length; i++) { 
     listBox1.Items.Add(bubble[i].ToString()); 
    } 

} 

희망을 설명 할 이하로 개선 된 코드를 가지고 있고 또한 당신이 더 나은 C# 코드를 작성하는 방법을 배울 수 있습니다.

1

두 가지 문제점이 있습니다. 하나는 구조체 자체의 속성이 아니라 구조체의 속성을 설정/교환하고 있습니다. 그래서 매출과 연도가 일치하지 않는 것입니다. 구조체 전체를 교환해야합니다. 예 :

    var temp = bubble[i]; 
        bubble[i] = bubble[i + 1]; 
        bubble[i + 1] = temp; 

두 번째 문제가 발생합니다. 인덱스 변수 i와 j를 사용하는 이중 루프가 있습니다. 스왑은 i만을 사용합니다. 버블 정렬을하려고한다면 정말로 중첩 된 루프가 필요합니까? 여기 bubble sort에서 찾을 수있는 의사 코드 구현을 고려하면 신속하게 문제를 볼 수 있어야합니다. 이 예제 다음에 정렬을 모델링하십시오.

+0

그게 사실이지만, 배열 (SSales [] bubble = 새로운 SSales [10])로 구조체를 사용하고 있지만 var temp를 어떻게 할당합니까? – user7115764

+0

예제에서와 같이 임시 변수를 할당 할 수 있습니다. 기본적으로 전체 구조체를 할당합니다. 타입에 대해 걱정할 필요가없는 'var'키워드를 사용함으로써, 컴파일러는 적절한 타입을 사용할 것입니다. – Dweeberly

관련 문제