help with sort function

조회 수: 5 (최근 30일)
zhi zhu
zhi zhu 2017년 3월 14일
댓글: zhi zhu 2017년 3월 14일
I am writing my own sorting function, I've gotten the minimum value for the array and set that to the other array, and I couldn't figure out how to get rid of that minimum value in the original array and tell the program to find the next smallest minimum value. Here's my code so far
clear,clc;
x = [6 5 3 5 9 10 438 4 1 4 7 0 4 8 4 2];
len = length(x);
minval = x(1);
for n = 1:len
for i = 1:len
if x(i) < minval
minval = x(i);
end
end
sortval(n) = minval;
end
disp(sortval)
I was thinking maybe I could delete that value, but doing that would change the size of the array and it wouldn't work.
  댓글 수: 1
John BG
John BG 2017년 3월 14일
편집: John BG 2017년 3월 14일
Hi Zhi
It's rewarding to be able to develop your own tools, yet sometimes, if time is of essence, on budget, perhaps you would like to consider having a look at a lost of already implemented sorting algorithms, here:
The one you want to implement, i think it's the bubble one.
Regards
John BG

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 3월 14일
편집: Jan 2017년 3월 14일
You can sort the vector "inplace": Move the minimum value to front and start the next iteration at the next element:
x = [6 5 3 5 9 10 438 4 1 4 7 0 4 8 4 2];
len = length(x);
for n = 1:len
minind = n;
minval = x(n);
for i = n+1:len % Start at n+1
if x(i) < minval
minval = x(i);
minind = i; % Remember index
end
end
tmp = x(n); % Swap current with minimal element
x(n) = minval;
x(minind) = tmp;
end
Finally x contains the sorted array and the processing time is reduced, because the inner loop is shortend. (By the way: You can omit the last iteration)
Have fun with developping sorting algorithms. This is an interesting topic and it is worth to dig in WikiPedia.

추가 답변 (1개)

the cyclist
the cyclist 2017년 3월 14일
편집: the cyclist 2017년 3월 14일
I have not looked in detail at your algorithm. But one possibility that springs to mind is that you could swap NaN in place of the element you want to eliminate. That will retain the size of the array, and NaN will never be selected as less than any other element, because the logical operation
NaN < x
will return false for any value of x.
  댓글 수: 3
the cyclist
the cyclist 2017년 3월 14일
Can you post the new code?
zhi zhu
zhi zhu 2017년 3월 14일
clear,clc;
x = [6 5 3 5 9 10 438 4 1 4 7 0 4 8 4 2];
len = length(x);
minval = x(1);
for n = 1:len
for i = 1:len
if x(i) < minval
minval = x(i);
end
end
for j = 1:len
if x(j) == minval
x(j) = NaN;
end
end
for r = 1:len
if x(r) == minval
x(r) = NaN;
end
end
sortval(n) = minval;
end
disp(sortval)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by