开发者

Check the sortedness Of An Array

开发者 https://www.devze.com 2022-12-12 20:55 出处:网络
I need an Algorithm which is used to find the N开发者_运维问答-element randomly-ordered integer

I need an Algorithm which is used to find the N开发者_运维问答-element randomly-ordered integer array is either already sorted or not.


Just loop through the array til you find an element that is less than the previous one. In C/Java'ish pseudo-code:

int prev = array[0];
boolean sorted = true;
for (int i=1; i<array.length; i++) {
  if (array[i] < prev) {
    sorted = false;
    break;
  }
  prev = array[i];
}


Test if ascending:

for item i in items
    if i > nextitem
       return false

return true
0

精彩评论

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

关注公众号