Hi, i am currently trying to use a bubble sort for a series of inputed numbers but im getting an error on line 2.
can someone please explain why i am getting this error and how to fix it.
thank you in advance.
here is my code and the error: Error in Bubble1 (line 2)
cases = input('Enter cases with [ ] around them:');
cases = input('Enter cases with [ ] around them:');
sorted_array = bubble_sort(cases)
function array = bubble_sort( array )
for i = 1:length(array)
for j = 1:length(array)-i
if(array(j)>array(j+1))
temp = array(j+1);
array(j+1) = array(j);
array(j) = temp;
end
end
end
end

 채택된 답변

Chunru
Chunru 2021년 9월 12일
편집: Chunru 2021년 9월 12일

0 개 추천

You code can run. if you use "input", key in the following "[1 3 2 5 2]" without quotes.
%cases = input('Enter cases with [ ] around them:');
cases = [1 3 2 5 2]
cases = 1×5
1 3 2 5 2
sorted_array = bubble_sort(cases)
sorted_array = 1×5
1 2 2 3 5
function array = bubble_sort( array )
for i = 1:length(array)
for j = 1:length(array)-i
if(array(j)>array(j+1))
temp = array(j+1);
array(j+1) = array(j);
array(j) = temp;
end
end
end
end

댓글 수: 4

Joe Ainsworth
Joe Ainsworth 2021년 9월 12일
Sorry @Chunru, i know it can run without the input line but i need the user to input the integers they would to bubble sort, how do i do this where the user can input the integers.
Walter Roberson
Walter Roberson 2021년 9월 12일
Using exactly the code you posted:
>> q1451489
Enter cases with [ ] around them:[1 3 2 5 2]
sorted_array =
1 2 2 3 5
That is, the user must enter the actual [ and ] characters as part of their input.
Joe Ainsworth
Joe Ainsworth 2021년 9월 12일
@Walter Roberson for whatever reason my code is working perfectly now, before it wouldnt even let me run it saying error on line 2
Joe Ainsworth
Joe Ainsworth 2021년 9월 12일
Thanks though!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품

릴리스

R2021a

태그

질문:

2021년 9월 12일

댓글:

2021년 9월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by