Sorting a Crimson 3 integer array in ascending order

bbaker123

Member
Join Date
Feb 2016
Location
Indiana
Posts
2
Hello all,

I've used these forums quite a bit in the past year while trying to learn PLCs and HMIs, and I've run across my first problem that I've not been able to find the answer to. I am trying to sort an integer array in ascending order, and I think I have the code correct, but it keeps displaying in descending order. Could you look at my code and see if I have overlooked something?

//Sorts Odd_Polar_Number[] array in ascending order.
for(i = 0 ; i < max_odd ; i++)
{
for(j = 1; j < max_odd - 1 ; j++)
{
if(Odd_Polar_Number > Odd_Polar_Number[j]) //If first array element is greater than second array element.
{
//Swaps array position.
swap = Odd_Polar_Number;
Odd_Polar_Number = Odd_Polar_Number[j];
Odd_Polar_Number[j] = swap;
}
}
}

Thanks!
 
Looks like you're trying to implement a bubble sort here, correct?

You need to compare adjacent pairs of numbers, but note that as your inner loop executes, the indices i and j will no longer refer to adjacent numbers in the array. You should be testing if Number[j] > Number[j+1]. Similarly, you need to swap the numbers at j and j+1. You'll also miss the first element if the inner loop doesn't start at j=0.

Making those changes gets something like this:

Code:
for(i = 0; i < max_odd; i++)
{
  for(j = 0; j < max_odd - 1 ; j++)
  {
    if(Odd_Polar_Number[j] > Odd_Polar_Number[j+1])
    {
       int swap = Odd_Polar_Number[j];
       Odd_Polar_Number[j] = Odd_Polar_Number[j+1];
       Odd_Polar_Number[j+1] = swap;
    }
  }
}
 

Similar Topics

I have worked on small projects using AB Micrologix but now we want to take a photo, process it online, and sort based on returned variables...
Replies
5
Views
315
Hi, I have just started with WinCC unified (v17) and there are alot of things I used on Comfort but now are not available. Currently I am finding...
Replies
3
Views
2,799
I'm trying to be smart about naming my tags so things automatically group together alphabetically, but for some reason it doesn't work like I...
Replies
15
Views
3,630
Hello friends. There is an int type, number that I got from the DataBlock. For example, the DataBlock address is Db1.dbw0. Here's what I want to...
Replies
32
Views
10,433
Good afternoon all, I am working on a college project where we have to sort 3 different color legos. Orange, Black, and Tan. I am using a color...
Replies
30
Views
6,760
Back
Top Bottom