image thumbnail
from Merge sort of Multidimensional array by Chandan
Sorting of array both single or multidimensional using Merge sorting technique.

readfile()
% AUTHOR    :CHANDAN KUMAR 
% TITLE     :MERGE SORT
% SUBJECT   :SORTING 
% DISCLAIMER:SORTS THE MULTI ROW OR COLUMN DATA USING MERGE SORT TECHNIQUE.



function readfile()
clc,clear all
Transpose_index =0;
[Fname,pname,findex] = uigetfile({'*.xls','Excel Sheet format(*xls)';...
    '*.mat','Mat file';'*.txt','Text file'},'Select the data file');
switch findex
    case 1    
        data = xlsread(Fname,'Sheet1');
    case 2
         load(Fname);
         whos
         data = input('Select the variable from above list') 
    case 3
        data = textread(Fname); 
end
[a,b] = size(data) ;
if (a ~=1)&(b ~=1)
    disp(data);
    disp('Data has more than one row.');
    option = input('Sorting has to be done according to Row or Column?(R/r OR C/c)','s');
    if (option == 'C')||(option == 'c')
        data = data'; [a,b] = size(data); Transpose_index = 1;
        disp('Sorting option for column:')
        disp('1.Sorting of one single column all other columns untouched.')
        disp('2.Sorting of all other column according to selected column.')
    else
        disp('Sorting option for row:')
        disp('1.Sorting of one single row all other rows untouched.')
        disp('2.Sorting of all other rows according to selected row.') 
    end
    R_option = input('Your option? '); 
    N_row = input('Row or Column index for sorting is? '); 
    if(R_option == 1)
        sort_data = mergesort(data,1,b,N_row,1);  
    else
        sort_data = mergesort(data,1,b,N_row,-1);
    end 
elseif(a ==1)
    sort_data = mergesort(data,1,b,1,1);
elseif(b ==1)
    data = data'; Transpose_index = 1;
    sort_data = mergesort(data,1,a,1,1);
end

if (Transpose_index == 1)
    sort_data = sort_data';
end
disp(sort_data)



function array = mergesort(array,low,high,index1,index2)
if(index2 == 1)
    mov_index = index1;
else
    [a1,b1] = size(array);
    mov_index = 1:a1;
end
if(high-low >= 1)
    middle = floor((low+high)/2 );
    end_low = middle;
    start_high = middle +1;
    array = mergesort(array,low,end_low,index1,index2) ;
    array = mergesort(array,start_high,high,index1,index2); 
    while(low <= end_low) & (start_high <= high)
        if (array(index1,low) < array(index1,start_high)) 
            low = low + 1;
        else
            Temp(mov_index,:) = array(mov_index,start_high);
            for k = start_high - 1: -1: low 
                array(mov_index,k+1) = array(mov_index,k);
            end
            array(mov_index,low) = Temp(mov_index,:);
            low = low + 1;
            end_low = end_low + 1;
            start_high = start_high + 1;
        end
    end
end

Contact us at files@mathworks.com