Total Pageviews

Tuesday 9 December 2014

Insertion Sort Using Excel VBA

Many of these sorting algorithm are written in C , C++ and Java.

Same programming  technique is used to develop algorithm using Excel VBA.

How to start ?
1. Copy the below code
2. Open the workbook in which you want to add the code
3. Hold the Alt key, and press the F11 key, to open the Visual Basic Editor
4. Choose Insert | Module
5. Where the cursor is flashing, choose Edit | Paste

How to  run the code?
1. On the Excel Ribbon, click the View tab
2. At the far right, click Macros
3. Select a macro in the list, and click the Run button


 Sub Insertion_Sort()
 Dim Num        As Integer
 Dim C          As Integer
 Dim D          As Integer
 Dim Temp       As Integer
 Dim Arr(1000)  As Integer
 
 Num = InputBox("Enter the number of elements")
 For C = 0 To Num - 1
      Arr(C) = InputBox("Enter the number ")
 Next C
 For C = 1 To Num - 1
        D = C
        Do While D > 0 And (Arr(D) < Arr(D - 1))
            Temp = Arr(D)
            Arr(D) = Arr(D - 1)
            Arr(D - 1) = Temp
            D = D - 1
            If D = 0 Then Exit Do
        Loop
 Next C
 For C = 0 To Num - 1
   Range("A" & C + 1).Value = Arr(C)
 Next C
 End Sub


No comments:

Post a Comment