开发者

Implementing a bubble sort to a class with multiple variable types in C#

I have a class that contains a few strings, as well as a few integer values. The program needs to use bubble sort to sort by a specific integer within called studentID.

The issue I'm coming across is accessing the variable properly. We are required to keep the variables within the class private, so the raw values aren't directly a开发者_开发技巧ccessible from anywhere other than inside the actual class.

I've got something like this set up

public class Student {
    // PRIVATE strings and ints

    public Student() {
        // set variables to text fields
    }

    public void bubbleSort() {
        int i, j, temp;

        for (i = (x-1); i >= 0; i--) {    
            for (j = 1; j <= i; j++) {    
                if(x[j - 1] > students[j]) {
                    temp = x[j - 1];
                    x[j - 1] = x[j];
                    x[j] = temp; 
                }
            } 
        }
    } 
}

For every occurrence of X, I need to have the value of myStudent.studentID. The bubble sort is meant to be implemented within the class, but I can't figure out how to call it. With the needed fields set to private, I can find no way to pull the information to be sorted.


Implement IComparable interface in Student class, and then use CompareTo() instead of "<" operator in bubbleBort. This will solve the issue with private variable.

And after these changes BubbleSort can be rewritten as static generic method.

public static void bubbleSort<T>(T[] array) where T : IComparable{
    int i, j;
    T temp;

    for (i = (x-1); i >= 0; i--) 
{    
    for (j = 1; j <= i; j++) 
{    
    if(array[j - 1].CompareTo(array[j]) == 1) 
{
    temp = array[j - 1];
    array[j - 1] = array[j];
    array[j] = temp; 
} } } }


You use properties to expose private fields to the outside.

private string text = "";

public string Text
{
  get { return text; }
  set { text = value; }
}

If you aren't allowed to do that, you should talk with your teacher, as interacting with the class isn't possible then.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜