Что самый изящный путь к пузырьковой сортировке в C#?

Переопределение didSelectRowAtIndexPath: и потяните UIView цвета Вашего выбора и вставьте его позади UILabel в ячейке. Я сделал бы это что-то вроде этого:

UIView* selectedView; //inside your header

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

  UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
  selectedView = [[UIView alloc] initWithFrame:[cell frame]];
  selectedView.backgroundColor = [UIColor greenColor]; //whatever

  [cell insertSubview:selectedView atIndex:0]; //tweak this as necessary
  [selectedView release]; //clean up

}

можно принять решение анимировать это представление, когда оно является невыбранным и удовлетворит требования.

6
задан alain.janinm 1 May 2012 в 10:01
поделиться

7 ответов

What you've pasted there isn't a bubble sort. It's a sort of "brute force" sort but it's not bubble sort. Here's an example of a generic bubble sort. It uses an arbitrary comparer, but lets you omit it in which case the default comparer is used for the relevant type. It will sort any (non-readonly) implementation of IList, which includes arrays. Read the above link (to Wikipedia) to get more of an idea of how bubble sort is meant to work. Note how on each loop we go through from start to finish, but only compare each item with its neighbour. It's still an O(n2) sort algorithm, but in many cases it will be quicker than the version you've given.

public void BubbleSort<T>(IList<T> list)
{
    BubbleSort<T>(list, Comparer<T>.Default);
}

public void BubbleSort<T>(IList<T> list, IComparer<T> comparer)
{
    bool stillGoing = true;
    while (stillGoing)
    {
        stillGoing = false;
        for (int i = 0; i < list.Count-1; i++)
        {
            T x = list[i];
            T y = list[i + 1];
            if (comparer.Compare(x, y) > 0)
            {
                list[i] = y;
                list[i + 1] = x;
                stillGoing = true;
            }
        }
    }
}
35
ответ дан 8 December 2019 в 02:02
поделиться

The most elegant way to sort in C# is

Array.Sort( object[] )

That will work everywhere except in homework problems where the teacher asked you to implement the non-elegant bubble sort algorithm. ;-)

13
ответ дан 8 December 2019 в 02:02
поделиться

Overall, there's nothing wrong with your bubble sort implementation. If I were doing a real code review, I'd make the following changes:

Choose more descriptive variable names

Why is your array just called c?

Minimize variable scope

All of your variables are declared at the top of the function. Unless this is a homework requirement or a coding standard, its more idiomatic to declare variables "close" to the location where they are used, preferably so they have the smallest amount of scope possible.

So, eliminate the first line which reads int i = 0,j = 0,t = 0;. Declare loop counters inline:

for(int i = 0; i < 20; i++)

And declare your temp variable in the place where its used:

                Console.WriteLine("c[{0}]={1}, c[{2}]={3}", i, c[i], j, c[j]);
                int t=c[i];
                c[i]=c[j];
                c[j]=t;

Eliminate hard-coded array bounds.

This:

for(i=0;i<20;i++)

Becomes this:

for(i = 0; i < c.Length; i++)
8
ответ дан 8 December 2019 в 02:02
поделиться

Большинство людей не потрудились бы создать пузырьковая сортировка элегантная. Однако в общем я обнаружил, что выполнение этого:

for (int i = 0; i < items.Length; i++) {
    Item item = items[i];
    // do something with item
}

более элегантно и более удобно в обслуживании, чем выполнение этого:

Item item;
int i;
for (i = 0; i < items.Length; i++) {
    item = items[i];
    // do something with item
}

Другими словами, объявляет ваши переменные в пределах наименьшей применимой области . В противном случае вы можете обнаружить, что делаете что-то с i или элемент в каком-то другом месте кода, а затем снова используете их там, где вам не должно быть.

3
ответ дан 8 December 2019 в 02:02
поделиться
  • I would use a swap methed to swap the two array items. (details of how to write swap method left as homework!)

  • You should think about the case when the items are already in order

  • You should read up on Insertion sort for more marks :-)

  • Rather then reading the test data from the keyboard, see if you can learn how to use nUnit

2
ответ дан 8 December 2019 в 02:02
поделиться

I personally prefer this:

string foo [] = new string[] {"abc", "def", "aaa", "feaf", "afea" };
Array.Sort(foo);

But that's just me. Sort is a solved problem, why reinvent the wheel?

1
ответ дан 8 December 2019 в 02:02
поделиться

I think your algorithm in ok, but I would put the sort functionality in a seperate class and method.

0
ответ дан 8 December 2019 в 02:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: