matrix sorting different way

6 Ansichten (letzte 30 Tage)
Lucy Hannah
Lucy Hannah am 1 Mai 2019
for example I have [ 1 9 5 7 8 4 6 2 3]
I want to sort by becoming [max, function , min]
where this function is basically taking the list without the first max and min and do it again [max, function,min]
so it become like [max,[max,[max,[max, function,min],min],min],min]
[9 8 7 6 5 4 3 2 1]
without using the sort(matrix)
  4 Kommentare
Lucy Hannah
Lucy Hannah am 1 Mai 2019
Bearbeitet: Lucy Hannah am 1 Mai 2019
im confused on how to do sorting without using the sort function thats my idea but maybe im wrong
Walter Roberson
Walter Roberson am 1 Mai 2019
Consider
A = [1 9 5 7 8 4 6 2 3]
Now suppose you cannot use sort(), but you can use max():
Result = [];
while ~isempty(A)
[maxval, maxidx] = max(A);
Result = [Result, maxval];
A(maxidx) = [];
end
The first step initialized Result to empty.
We then test, is A not empty? Is is not empty, so we do the steps. We find the maximum value of A, which is 9, and assign that to maxval, and we assign the index of that maximum inside A, 2, to maxidx. We then append the maximum value we just got, 9, to Result, giving us Result = [9] . We then delete A(2), giving use A = [1 5 7 8 4 6 2 3]. We loop back.
A is still not empty, so max(A) gives us maxval = 8, maxidx = 4, and we append the 8 to Result giving us Result = [9 8], and we remove A(4) giving us A = [1 5 7 4 6 2 3]. We loop back
A is still not empty, so max(A) gives us maxval = 7, maxidx = 3, and we append the 7 to Result giving [9 8 7], and we remove A(3) giving us A = [1 5 4 6 2 3]. We loop back
Next, 6 @ 4, Result = [9 8 7 6], A = [1 5 4 2 3]
Next, 5 @ 2, Result = [9 8 7 6 5], A = [1 4 2 3]
Next, 4 @ 2, Result = [9 8 7 6 5 4], A = [1 2 3]
Next, 3 @ 3, Result = [9 8 7 6 5 4 3], A = [1 2]
Next, 2 @ 2, Result = [9 8 7 6 5 4 3 2], A = [1]
Next, 1 @ 1, Result = [9 8 7 6 5 4 3 2 1], A = []. We loop back
A is now empty so we stop looping.
Now Result is the original A sorted in reverse order, but we never used sort(). Instead, at each step, we found the maximum and removed it from the array, and then processed what was left of the array.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by