MATLAB: Sorting a list of numbers from one file then writing to a second file

bubble sortMATLABsorting a listwriting to file

Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position.
The resulting array after k iterations has the property where the first k + 1 entries are sorted ("+1" because the first entry is skipped). In each iteration the first remaining entry of the input is removed, and inserted into the result at the correct position, thus extending the result:
Write a program that uses the Insertion sort algorithm to sort a list of numbers that are read in from a file (random.txt) and then writes the sorted numbers to a second file.
Heres what I have so far
x = load('random.txt');
lengthofarray = length(x);
fileID = fopen('random.txt');
fprintf(fileID,x);
fclose(fileID);
for i = 1:lengthofarray
for j = 1:(lengthofarray – i)
if x(j)> x(j+1)
temp=x(j);
x(j)=x(j+1);
x(j+1)=temp;
end
end
end

Best Answer

Hi,
Here is the complete solution of your exercise:
x = load('random.txt'); X1=x;
XX = sort(x); % This sorts all values of the read x in the ascending order
%% Writes the sorted data to an external file called Random2.txt
dlmwrite('Random2.txt', XX, 'delimiter', '\t');
dlmread('Random2.txt') % displays in the command window
%% This loop operation is slow and very inefficient
% L = length(x);
% for i = 1:L
% for j = 1:L- i
% if x(j)> x(j+1)
% temp=x(j);
% x(j)=x(j+1);
% x(j+1)=temp;
% end
% end
% end
Good luck.
Related Question