Блог пользователя visitorG

Автор visitorG, история, 7 недель назад, По-английски

Hey,

In this blog, I will tell you, how to sort a vector without sort(a.begin(), a.end()) because I don't know how it works. So I just randomly made this( I don't really know If it ever existed, so just listen to what I say because I spent 30 minutes just figuring out the idea..)

void sort() {
  int n;
  cin >> n;
  vector<int>a(n);
  for(int i=0;i<n;i++) {
    cin >> a[i];
  }
  while(!(is_sorted(a.begin(), a.end()))) {
    for(int i=1;i<n;i++) {
      if(a[i]<a[i-1]) {
        swap(a[i], a[i-1]);
      }
    }
  }
  for(auto e:a) {
    cout << e << " ";
  }
  cout << endl;
}

I wont add comments, because that will make me look like a cheater. So, Listen to this:

"What I did in here was I first checked if the list was not sorted and then a simple loop. The main thing comes now, I checked whether a[i] is less than a[i-1] and if it was, I would just simply swap them(that was kinda simple tbh). Afterwards I just "couted" them."

I think that you might have understand what I just told you about "Sorting".

UPDATE: The reason why I made this is to show you how sorting works, not to use it.

  • Проголосовать: нравится
  • -20
  • Проголосовать: не нравится

»
7 недель назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Perhaps you need to understand the difference between O(n^2) and O(n log n).

»
7 недель назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Your sorting function is essentially bubble sort, but it could be optimized to O(n^2). Its better to use the built-in sort function, which runs in O(n log n) time. If you're looking for the way to sort vector without using built-in sort , better use merge sort or heap sort algorithms which runs in O(n log n) time also

»
7 недель назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

This is O(n log n).

void solve() {
  int n;
  cin >> n;
  vector<int>a(n);
  for(int i=0;i<n;i++) cin >> a[i];
  
  sort(all(a));
  
  for(auto e:a) {
    cout << e << " ";
  }
  cout << endl;
}
»
6 недель назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by visitorG (previous revision, new revision, compare).